54. 螺旋矩阵
https://leetcode.cn/problems/spiral-matrix/description/
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
class Solution {
private List<int[]> vector = Arrays.asList(
new int[]{0,1},
new int[]{1, 0},
new int[]{0,-1},
new int[]{-1, 0}
);
private boolean over(int x, int y, int m, int n) {
return x < 0 || y < 0 || x >= m || y>= n;
}
public List<Integer> spiralOrder(int[][] matrix) {
int d = 0;
int m = matrix.length;
int n = matrix[0].length;
int x = 0;
int y = -1;
int xx; int yy;
boolean[][] visit = new boolean[m][n];
List<Integer> res = new ArrayList<>();
while (true) {
xx = x + vector.get(d % 4)[0];
yy = y + vector.get(d % 4)[1];
if (over(xx, yy,m,n) || visit[xx][yy]) {
d += 1;
continue;
}
res.add(matrix[xx][yy]);
visit[xx][yy] = true;
x = xx; y = yy;
if (res.size() >= m *n){
break;
}
}
return res;
}
}