自己写的是使用两个四维的旋转矩阵,再加一个visited访问boolean访问数组
以下代码相对就简洁很多。
代码来源:
作者:Krahets
https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solution/mian-shi-ti-29-shun-shi-zhen-da-yin-ju-zhen-she-di/
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0) return new int[]{};
int l = 0,r = matrix[0].length - 1,t = 0,b = matrix.length - 1;
int[] res = new int[(r + 1) * (b + 1)];
int x = 0;
while(true){
for(int i = l;i <= r;i++) res[x++] = matrix[t][i];
if(++t > b) break;
for(int i = t;i <= b;i++) res[x++] = matrix[i][r];
if(--r < l) break;
for(int i = r;i >= l;i--) res[x++] = matrix[b][i];
if(--b < t) break;
for(int i = b;i >= t;i--) res[x++] = matrix[i][l];
if(++l > r) break;
}
return res;
}
自己写的代码:
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return new int[0];
int row = matrix.length;
int col = matrix[0].length;
int[] res = new int[row * col];
int index = 1;
int[] xDir = {0,1,0,-1};
int[] yDir = {1,0,-1,0};
int x = 0;
int y = 0;
res[0] = matrix[0][0];
boolean[][] visited = new boolean[row][col];
visited[0][0] = true;
while (index < res.length){
for (int i = 0; i < 4; i++) {
while (x + xDir[i] >=0 && y + yDir[i] >= 0 &&x + xDir[i] < row && y + yDir[i] < col
&& !visited[x + xDir[i]][y + yDir[i]]){
x += xDir[i];
y += yDir[i];
res[index++] = matrix[x][y];
visited[x][y] = true;
}
}
}
return res;
}