第一眼看到这个题,感觉和LeetCode上的59. Spiral Matrix II 很像。但是这个题比那个要复杂。LeetCode上的那个题,只需要不停按圈顺时针遍历,使用二维数组的值是否为0来判断边界。其代码如下:
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int x = 0, y = -1, count = 1;
while (count <= n * n) {
while (++y < n && res[x][y] == 0) res[x][y] = count++;
y--;
while (++x < n && res[x][y] == 0) res[x][y] = count++;
x--;
while (--y >= 0 && res[x][y] == 0) res[x][y] = count++;
y++;
while (--x >= 0 && res[x][y] == 0) res[x][y] = count++;
x++;
}
return res;
}
}
这个题不同的地方,只是需要手动设置4个变量来记录之前遍历过的边界,在代码中体现为x1,x2,y1,y2。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return res;
// 矩阵的行数和列数
int row = matrix.length, col = matrix[0].length;
// 当前位于矩阵的位置
int x = 0, y = -1;
// x1和x2分别代表当前允许的行数的最小值和最大值
// y1和y2分别代表当前允许的列数的最小值和最大值
int x1 = 1, x2 = row - 1, y1 = 0, y2 = col - 1;
// 一共需要输出的数字个数
int count = row * col;
while (res.size() < count) {
// 从左上往右上遍历
while (++y <= y2) res.add(matrix[x][y]);
y--;
y2--;
// 从右上往右下遍历
while (res.size() < count && ++x <= x2) res.add(matrix[x][y]);
x--;
x2--;
// 从右下往左下遍历
while (res.size() < count && --y >= y1) res.add(matrix[x][y]);
y++;
y1++;
// 从左下往左上遍历
while (res.size() < count && --x >= x1) res.add(matrix[x][y]);
x++;
x1++;
}
return res;
}
}
这个题目中还需要注意的地方是,不要把矩阵看成行列相等,并且要注意特殊输入,比如数组只有一个数、数组只有一行、数组只有一列、数组只有一行一列的情况。