题目描述
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
分析
旋转挨个输出即可
代码
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new LinkedList<>();
if(matrix == null || matrix.length == 0) return null;
int left = 0;
int right = matrix[0].length - 1;
int top = 0;
int bottom = matrix.length - 1;
int numAll = matrix.length * matrix[0].length;
while(numAll >= 1) {
for(int i = left; i <= right && numAll >= 1; i++) {
res.add(matrix[top][i]);
numAll--;
}
top++;
for(int i = top; i <= bottom && numAll >= 1; i++) {
res.add(matrix[i][right]);
numAll--;
}
right--;
for(int i = right;i >=left && numAll >=1; i--) {
res.add(matrix[bottom][i]);
numAll--;
}
bottom--;
for (int i = bottom; i >= top && numAll >= 1; i--) {
res.add(matrix[i][left]);
numAll--;
}
left++;
}
return res;
}