原题链接:
https://leetcode.cn/problems/spiral-matrix/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
右下左上
*/
class Solution {
// 注意一下坐标就行了 程序中的坐标系会与传统理解坐标系有些不同
public int [] dx = new int [] {0,1,0,-1};
public int [] dy = new int [] {1,0,-1,0};
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean [][] vis = new boolean [m][n];
ArrayList<Integer> res = new ArrayList<>();

int cur = 0;
int x = 0, y = 0;
int d = 0;
while(cur != m * n){
res.add(matrix[x][y]);
vis[x][y] = true;
cur++;
int tx = x + dx[d];
int ty = y + dy[d];
if( tx < 0 || ty < 0 || tx == m || ty == n || vis[tx][ty]){
d = (d + 1) % 4;
tx = x + dx[d];
ty = y + dy[d];
}
x = tx;
y = ty;
}

return res;
}
}