题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
输入: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]
代码
打印顺序 “从左向右、从上向下、从右向左、从下向上” 循环,
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
//定义左右上下四个边界
int left = 0, right = matrix[0].length - 1, top = 0, botton = matrix.length - 1;
int x = 0;//数组自增标志位
int[] result = new int[(right + 1) * (botton + 1)];
while (true) {
//从左往右遍历
for (int i = left; i <= right; ++i)
result[x++] = matrix[top][i];
//从左往右每遍历完一行就意味着上边界往下移动一行,
if (++top > botton) break;
//从上往下遍历
for (int i = top; i <= botton; ++i)
result[x++] = matrix[i][right];
//从上往下遍历完一列意味着右边界往左移动一列
if (--right < left) break;
//以下同理
for (int i = right; i >= left; --i)
result[x++] = matrix[botton][i];
if (--botton < top) break;
for (int i = botton; i >= top; --i)
result[x++] = matrix[i][left];
if (++left > right) break;
}
return result;
}
}