给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
分析:行数最小是1 说明只要给的数组不是null 就行
思路
:设定四个指针 left 、right、top、bottom

class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if(matrix==null) return null;
List<Integer> list = new ArrayList();
int top = 0;
int bottom = matrix.length - 1;//有多少组数组就是代表有多少行
int left = 0;
int right = matrix[0].length - 1;//第0行数组有多少个元素表示有多少列
//一轮循环后 top > bottom 或 left > right 就退出
while(top <= bottom && left <= right) {
//top left --> top right
for(int i = left; i <= right; i++) {
list.add(matrix[top][I]);
}
top++;
//top right --> right bottom
for(int i = top; i <= bottom; i++) {
list.add(matrix[i][right]);
}
right--;
//top 和 right 移动后需要查看是否跑过了的情况;不处理 奇数行 或 偶数列会出问题
if(top > bottom || left > right) break;
//right bottom --> left bottom
for(int i = right; i >= left; i--){
list.add(matrix[bottom][I]);
}
bottom--;
//left bottom --> left top
for(int i = bottom; i >= top; i--){
list.add(matrix[i][left]);
}
left++;
}
return list;
}
}
网友评论