0%

leetcode 54 Solution

代码解析

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
package com.demo.s54;

import java.util.ArrayList;
import java.util.List;

/**
* 螺旋矩阵
* 给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
*
*/
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ret = new ArrayList();
if(matrix == null || matrix.length ==0 || matrix[0].length ==0) {
return ret;
}
//判断需要旋转的几个方向
int[][] dirs = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
//行数
int m = matrix.length;
//列数
int n = matrix[0].length;
int[][] visited = new int[m][n];
int i =0;
int j =0;
//方向
int directions = 0;
for(int cnt = 0; cnt < m*n; cnt++) {
//已访问
visited[i][j] = 1;

ret.add(matrix[i][j]);

//下一个节点对应的行 遍历的方向 dirs[directions][0] 控制
int nexti = i + dirs[directions][0];
//下一个节点对应的列 遍历的方向 dirs[directions][1] 控制
int nextj = j + dirs[directions][1];
//边界判断
if(nexti < 0 || nexti > m-1 || nextj < 0 ||nextj > n-1 || visited[nexti][nextj] == 1 ) {
directions = (directions+1) % 4;
}
//行数变更 + 1 或者 不变
i = i + dirs[directions][0];
//列数变更 + 1 或者 不变
j = j + dirs[directions][1];


}
return ret;
}
}