本题解析,主要是根据LeetCode官方给出的答案,进行每一步代码的详细介绍。原题链接https://leetcode-cn.com/problems/spiral-matrix/solution/luo-xuan-ju-zhen-by-leetcode-solution/
1.问题描述
2.思路
模拟螺旋矩阵的路径,假设初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,顺时针旋转,进入下一个方向,其中方向的转变是由给定的方向矩阵directions实现的。
判断路径是否进入之前访问过的位置需要使用一个与输入矩阵大小相同的辅助矩阵 visited,其中的每个元素表示该位置是否被访问过。当一个元素被访问时,将 visited 中的对应位置的元素设为已访问。
如何判断路径是否结束?由于矩阵中的每个元素都被访问一次,因此路径的长度即为矩阵中的元素数量,当路径的长度达到矩阵中的元素数量时即为完整路径,将该路径返回。
3.详细代码
public class Solution54 {
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new LinkedList<>();
if (matrix==null|| matrix.length==0||matrix[0].length==0){
return result;
}
//获取二维数组的行和列
int rows = matrix.length;
int columns = matrix[0].length;
//总共元素个数
int total = rows*columns;
//定义一个相同大小的辅助矩阵visited
boolean[][] visited = new boolean[rows][columns];
//定义一个方向矩阵directions
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
//定义遍历方向directionIndex
int directionIndex = 0;
//定义遍历启始位置
int row = 0;
int column = 0;
for (int i = 0;i<total;i++){
result.add(matrix[row][column]);
visited[row][column] = true;
//定义下一个遍历位置
int nextRow = row + directions[directionIndex][0],nextColumn = column + directions[directionIndex][1];
//根据边界条件,得出下一次遍历方向
if (nextRow>=rows||nextRow<0||nextColumn>=columns||nextColumn<0||visited[nextRow][nextColumn]){
directionIndex = (directionIndex + 1)%4;
}
row+=directions[directionIndex][0];
column+=directions[directionIndex][1];
}
return result;
}
}
4.运行结果