题目
代码
public class Solution {
public int[] spiralOrder(int[][] matrix) {
int row = matrix.length;
if (row == 0) return new int[0];
int col = matrix[0].length;
int[] res = new int[row * col];
int idx = 0;
int left = 0, top = 0, right = col - 1, bottom = row - 1;
while (true) {
for (int i = left; i <= right; i++) {res[idx++] = matrix[top][i];}
if (++top > bottom) break;
for (int i = top; i <= bottom; i++) {res[idx++] = matrix[i][right];}
if (--right < left) break;
for (int i = right; i >= left; i--) { res[idx++] = matrix[bottom][i];}
if (--bottom < top) break;
for (int i = bottom; i >= top; i--) { res[idx++] = matrix[i][left]; }
if (++left > right) break;
}
return res;
}
}
结果
|