题目:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:
- 0 <= matrix.length <= 100
- 0 <= matrix[i].length <= 100
题解:
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0)
return new int[0];
int m = matrix.length, n = matrix[0].length;
int[] res = new int[m * n];
//初始时up处于第一行,down最后一行,left在第一列,right在最后一列
int up = 0, down = m - 1, left = 0, right = n - 1, index = 0;
while (true) {
// 上面行,从左往右打印(行不变,改变列的下标)
for (int col = left; col <= right; col++)
res[index++] = matrix[up][col];
if (++up > down) break;
// 右边列,从上往下打印(列不变,改变行的下标)
for (int row = up; row <= down; row++)
res[index++] = matrix[row][right];
if (--right < left) break;
// 下面行,从右往左打印(行不变,改变列的下标)
for (int col = right; col >= left; col--)
res[index++] = matrix[down][col];
if (--down < up) break;
// 左边列,从下往上打印(列不变,改变行的下标)
for (int row = down; row >= up; row--)
res[index++] = matrix[row][left];
if (++left > right) break;
}
return res;
}
}