模拟 02
2021-03-15 本文已影响0人
眼若繁星丶
模拟 02
54. 螺旋矩阵.png
模拟即可
- 判断下一个左边边界是否溢出和是否遍历过,来决定是否改变方向
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return res;
}
int rows = matrix.length, cols = matrix[0].length, totalElements = rows * cols;
final int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
boolean visited[][] = new boolean[rows][cols];
int x = 0, y = 0;
int dirIdx = 0; // 0 ~ 3: turning right / down / left / up
for (int i = 0; i < totalElements; i++) {
res.add(matrix[x][y]);
visited[x][y] = true;
int nextX = x + dir[dirIdx][0], nextY = y + dir[dirIdx][1];
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols || visited[nextX][nextY]) {
dirIdx = (dirIdx + 1) % 4; // turning direction
}
x += dir[dirIdx][0];
y += dir[dirIdx][1];
}
return res;
}
}