题目描述
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
解法一
按照上图箭头画的顺序,一圈一圈的遍历
定义四个变量,来控制遍历过程中的边界
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return res;
}
int rows = matrix.length, columns = matrix[0].length;
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
res.add(matrix[top][column]);
}
for (int row = top + 1; row <= bottom; row++) {
res.add(matrix[row][right]);
}
if (left < right && top < bottom) { // 防止一行或一列的情况
for (int column = right - 1; column > left; column--) {
res.add(matrix[bottom][column]);
}
for (int row = bottom; row > top; row--) {
res.add(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return res;
}
方法二:
比较推荐这种方式,比较好理解
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return order;
}
int rows = matrix.length, columns = matrix[0].length;
boolean[][] visited = new boolean[rows][columns];
int total = rows * columns;
int row = 0, column = 0;
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int directionIndex = 0;
for (int i = 0; i < total; i++) {
order.add(matrix[row][column]);
visited[row][column] = true;
int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
directionIndex = (directionIndex + 1) % 4;
}
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return order;
}
方法三:递归
public static int[][] directions = {{0,1},{1,0},{0, -1},{-1, 0}};
//public static int direction = 0; 定义为static,在多次运行后,某一次开始是direction可能不是从0开始,所以测试用例报错了
public int direction = 0;
//定义一个标记矩阵,每次遍历完 matrix 的方格,用标记矩阵标记
public boolean[][] seen;
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int rows = matrix.length;
int cols = matrix[0].length;
seen = new boolean[rows][cols];
dfs(res, matrix, rows, cols, 0, 0);
return res;
}
public void dfs(List<Integer> res, int[][] matrix, int rowNums, int colNums, int x, int y) {
//判断条件:超出边界,或者遇到已经赋值过的方格
if (x < 0 || x >= rowNums || y < 0 || y >= colNums || seen[x][y] == true) {
//撞到墙了,需要转向
direction = (direction + 1) % 4;
return;
}
//标记该方格
seen[x][y] = true;
//添加该方格进数组
res.add(matrix[x][y]);
//循环供一次原方向,一次转向
for (int i = 0; i < 2; i++) {
int mx = x + directions[direction][0];
int my = y + directions[direction][1];
//递归下一个方格
dfs(res, matrix, rowNums, colNums, mx, my);
}
}
参考代码:官方题解