给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
解:边界收缩,定义四个边界top,right,bottom,left。顺时针遍历矩阵时,如果撞墙了,更换方向,并且收缩自己遍历的那个边界,(比如说1 -> 2 -> 3,遇到了right,跟换遍历方向,并且收缩top边界(top++))。直到边界收缩到top > bottom或者left > right。
思路:Krahets
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
// 边界收缩
if (matrix.length == 0) {
return new ArrayList<Integer>();
}
int left = 0;
int right = matrix[0].length - 1;
int top = 0;
int bottom = matrix.length - 1;
Integer[] res = new Integer[matrix.length * matrix[0].length];
int x = 0;
while (true) {
for (int i = left; i <= right; i++) {
res[x++] = matrix[top][i];
}
if (++top > bottom) break; // 上边界收缩
for (int i = top; i <= bottom; i++) {
res[x++] = matrix[i][right];
}
if (--right < left) break; // 右边界收缩
for(int i = right; i >= left; i--) {
res[x++] = matrix[bottom][i];
}
if(--bottom < top) break; // 下边界收缩
for(int i = bottom; i >= top; i--){
res[x++] = matrix[i][left];
}
if(++left > right) break; // 左边界收缩
}
return Arrays.asList(res);
}
}