题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
思考
- 设置上下左右边界,用for循环一圈一圈的进行顺时针输出
代码
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix.length == 0)
return new int[0];
int c = matrix[0].length, r = matrix.length;
int[] array = new int[c * r];
int count = 0, top = 0, bottom = r - 1,
left = 0, right = c - 1;
while (count != array.length) {
for (int i = left; i <= right; i++) {
if (count == array.length)
return array;
array[count++] = matrix[top][i];
}
for (int i = top + 1; i <= bottom; i++) {
if (count == array.length)
return array;
array[count++] = matrix[i][right];
}
for (int i = right - 1; i > left; i--) {
if (count == array.length)
return array;
array[count++] = matrix[bottom][i];
}
for (int i = bottom; i > top; i--) {
if (count == array.length)
return array;
array[count++] = matrix[i][left];
}
left++;
right--;
top++;
bottom--;
}
return array;
}
}