问题描述
给出一个 m x n 的矩阵(m 行, n 列),请按照
顺时针螺旋顺序返回元素。
例如,给出以下矩阵:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
应该返回 [1,2,3,6,9,8,7,4,5]
解题思路和分析
方法一:模拟
直觉就是按照这个顺时针的顺序将数组中的数字输出。
矩阵有R行,C列,seen[r][c]数组用来标记是否被访问过。我们现在的位置是[r][c],前进的方向是di,我们要把数组内的所有元素都访问一遍。
当我们在数组内移动的时候,我们候选的下一个位置是(cr,cc)。如果(cr,cc)属于这个矩阵并且还没有被访问过,那么我们就移动到(cr,cc)。否则,我们应该顺时针转弯了。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List ans = new ArrayList(); //存储结果
if (matrix.length == 0) return ans;
int R = matrix.length, C = matrix[0].length; //R行C列
boolean[][] seen = new boolean[R][C]; //boolean数组用来标记是否被访问过
int[] dr = {0, 1, 0, -1}; //表示方向
int[] dc = {1, 0, -1, 0};
int r = 0, c = 0, di = 0;
for (int i = 0; i < R * C; i++) {
ans.add(matrix[r][c]);
seen[r][c] = true;
int cr = r + dr[di];
int cc = c + dc[di];
if (0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr][cc]){
r = cr;
c = cc;
} else {
di = (di + 1) % 4;
r += dr[di];
c += dc[di];
}
}
return ans;
}
}
时间复杂度:O(n),n为矩阵中元素的数量,因为要把矩阵的每个元素添加到我们的结果中(ans);
空间复杂度:O(n),n为矩阵中元素的数量,seen和ans;
方法二:逐层
先输出最外层元素,再输出第二层的元素,以此类推。
![](https://i-blog.csdnimg.cn/blog_migrate/e3fa85710f8f6016664651df56596420.png)
class Solution {
public List < Integer > spiralOrder(int[][] matrix) {
List ans = new ArrayList(); //存储结果
if (matrix.length == 0) return ans;
int r1 = 0,
r2 = matrix.length - 1; //行数
int c1 = 0,
c2 = matrix[0].length - 1; //列数
while (r1 <= r2 && c1 <= c2) {
for (int c = c1; c <= c2; c++) {
ans.add(matrix[r1][c]); //将上面的行,向右,加入
}
for (int r = r1 + 1; r <= r2; r++) {
ans.add(matrix[r][c2]); //将右边的列,向下,加入
}
if (r1 < r2 && c1 < c2) {
for (int c = c2 - 1; c > c1; c--) ans.add(matrix[r2][c]); //将下面的行,向左顺序,加入
for (int r = r2; r > r1; r--) ans.add(matrix[r][c1]); //将左边的列,向行顺序,加入
}
//进入第次内层
r1++;
r2--;
c1++;
c2--;
}
return ans;
}
}
时间复杂度:O(n),n为矩阵中元素的数量,因为要把矩阵的每个元素添加到我们的结果中(ans);
空间复杂度:O(n),存储ans