题目描述
// 54. 螺旋矩阵
// 给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中
// 的所有元素。
题解
// 本题和【剑指offer】29. 顺时针打印矩阵 一模一样
//
// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:36.2 MB, 在所有 Java 提交中击败了99.12%的用户
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int row1 = 0;
int row2 = matrix.length - 1;
int col1 = 0;
int col2 = matrix[0].length - 1;
List<Integer> res = new ArrayList<>();
while (row1 <= row2 && col1 <= col2) {
printMatrix(matrix, row1, row2, col1, col2, res);
row1++;row2--;col1++;col2--;
}
return res;
}
public void printMatrix(int[][] matrix, int row1, int row2, int col1, int col2, List<Integer> res) {
for (int i = col1; i <= col2; i++) {
res.add(matrix[row1][i]);
}
for (int i = row1 + 1; i <= row2; i++) {
res.add(matrix[i][col2]);
}
if (row1 != row2) {
for (int i = col2 - 1; i >= col1; i--) {
res.add(matrix[row2][i]);
}
}
if (col1 != col2) {
for (int i = row2 - 1; i >= row1 + 1 ; i--) {
res.add(matrix[i][col1]);
}
}
}
}