# My JAVA solution

• cut the matrix into circles.like an onion.and every circle can be traversed by the same logic.
Left->Right,Up->Down,Right->Left,Down->Up;

``````public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if(matrix.length <= 0 ){
return result;
}
int h = 0;
int v = 0;
int hPlus = 0;
int vPlus = 1;
int m = matrix.length;
int n = matrix[0].length;
int length = m * n;
int vMin = 0;
int hMin = 1;
for (int i = 1; i <= length; i++) {
if (v + vPlus >= n && vPlus >0) {
hPlus = 1;
vPlus = 0;
}
else if (v + vPlus < vMin && vPlus <0) {
vPlus = 0;
hPlus = -1;
}
else if (h + hPlus >= m && hPlus >0) {
hPlus = 0;
vPlus = -1;
}
else if (hPlus<0 && h + hPlus < hMin) {
//reset traverse condition
hPlus=0;
vPlus = 1;
n--;
m--;
vMin++;
hMin++;
}

h += hPlus;
v += vPlus;
}

return result;
}``````

• ``````    public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length;
if (m <= 0) {
return list;
}
int n = matrix[0].length;
int[][] a = new int[m + 2][n + 2];
int[][] direction = {
{0, 1},
{1, 0},
{0, -1},
{-1, 0}
};
int x = 0, y = 0;
int dir = 0;
for (int i = 0; i < a.length; i++) {
a[i][0] = 1;
a[i][a[0].length - 1] = 1;
}
for (int i = 1; i < a[0].length - 1; i++) {
a[0][i] = 1;
a[a.length - 1][i] = 1;
}
while (true) {
a[x + 1][y + 1] = 1;
if (a[x + 1 + direction[dir][0]][y + 1 + direction[dir][1]] == 0) {
x += direction[dir][0];
y += direction[dir][1];
} else {
dir = (dir + 1) % direction.length;
if (a[x + 1 + direction[dir][0]][y + 1 + direction[dir][1]] == 0) {
x += direction[dir][0];
y += direction[dir][1];
} else {
break;
}
}
}
return list;
}``````

• yours is better to understand,thanks.
but it might cost more space,for using another matrix to store current state.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.