54-螺旋矩阵

54-螺旋矩阵

力扣54

https://leetcode-cn.com/problems/spiral-matrix/

我记得是在acwing里面学的,dx,dy作为导向,每次只要x += dx[t]即可,不用上下左右考虑是加还是减,还是很方便的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
int[] dx = {0, 1, 0, -1}; //方向指引
int[] dy = {1, 0, -1, 0};
int x = 0, y = -1, t = 0; //t代表第几次方向,x,y初值是因为一开始往右走
boolean[][] isPass = new boolean[matrix.length][matrix[0].length];
for(int i = 0; i < matrix.length * matrix[0].length; i++){
if(!check(matrix, x + dx[t], y + dy[t], isPass)){
//转向
t = (t + 1) % 4;
}
x += dx[t];
y += dy[t];
res.add(matrix[x][y]);
isPass[x][y] = true;
}
return res;
}

public boolean check(int[][] matrix, int x, int y, boolean[][] isPass){
return x >= 0 && x < matrix.length && y >= 0 && y < matrix[0].length && !isPass[x][y];
}

其他题目点击这里

Your browser is out-of-date!

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

×