LeetCode-螺旋矩阵
题目
思路
核心:
- 用数组
dx/dy
(direction of X/Y) 记录坐标x,y在移动的过程中的变化量
int[] dx = {0,1,0,-1};
int[] dy = {1,0,-1,0};
- 用一个二维数组
visited
来记录当前坐标是否已经被访问过
代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int m = matrix.length;
int n = matrix[0].length;
//corner case
if(m == 0) return res;
//用数组dx,dy预先设定坐标x、y在移动中的变化情况
int[] dx = {0,1,0,-1};
int[] dy = {1,0,-1,0};
//记录结点是否被访问过
boolean[][] isVisited = new boolean[m][n];
int d = 0;
//nx,ny表示下一个结点
int x = 0, y = 0, nx = 0, ny = 0;
//当res.size() != 矩阵的总大小,循环继续
while(res.size() != m * n){
res.add(matrix[x][y]);
isVisited[x][y] = true;
nx = x + dx[d];
ny = y + dy[d];
if(nx >= 0 && ny >= 0 && nx < m && ny < n && !isVisited[nx][ny]){
//不需要转向的情况,直接顺着当前方向往前走
x = nx;
y = ny;
}else{
//需要转向的情况,按照预设的转向设定进行转向
d = (d + 1) % 4;
nx = x + dx[d];
ny = y + dy[d];
x = nx;
y = ny;
}
}
return res;
}
}