第一眼看到這個題,感覺和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;
}
}
這個題目中還需要注意的地方是,不要把矩陣看成行列相等,並且要注意特殊輸入,比如數組只有一個數、數組只有一行、數組只有一列、數組只有一行一列的情況。