54. Spiral Matrix

54. 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<>();

int i=0,j=0;
int n=matrix.length;
if(n==0)return list;
int m = matrix[0].length;
int cnt = 0,loop=0;
while(cnt<m*n) {
while(cnt<n*m&&j<m-loop) {
list.add(matrix[i][j]);
cnt++;
j++;
}

j--;
i++;

while(cnt<m*n&&i<n-loop) {
list.add(matrix[i][j]);

i++;
cnt++;
}

i--;
j--;

while(cnt<m*n&&j>=loop) {
list.add(matrix[i][j]);
cnt++;
j--;
}
j++;
i--;

while(cnt<m*n&&i>loop) {
list.add(matrix[i][j]);
i--;
cnt++;
}
i++;
j++;
loop++;
//System.out.println(list);
}

return list;

}
}

整理后

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
  public List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<>();

int i=0,j=0;
int m=matrix.length;
if(m==0)return list;
int n = matrix[0].length;
int cnt = 0,loop=0;
while(cnt<m*n) {
i=loop;
j=loop;
for(int k=j; k<n-loop;k++,cnt++) {
list.add(matrix[i][k]);
}
j += n-loop-1;

for(int k=i+1;k<m-loop;k++,cnt++) {
list.add(matrix[k][j]);
}
i += m-loop-1;
for(int k=j-1; k>=loop;k--,cnt++) {
list.add(matrix[i][k]);
}
j = loop;
for(int k=i-1;k>loop;k--,cnt++) {
list.add(matrix[k][j]);
}

loop++;
//System.out.println(list);
}

return list;

}

直接使用一个循环

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
  public List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<>();

int i=0,j=0;
int m=matrix.length;
if(m==0)return list;
int n = matrix[0].length;

int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
int idx = 0;
for(int k=0;k<m*n;k++) {

list.add(matrix[i][j]);
matrix[i][j] = 1000;
int x = i + dirs[idx][0];
int y = j + dirs[idx][1];
if(x<0 || y<0 || x>=m || y>=n || (matrix[x][y]^1000)==0) {
idx = (idx + 1)%4;
x = i + dirs[idx][0];
y = j + dirs[idx][1];
}
i=x;
j=y;
}

return list;

}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×