螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int left=0, up=0, down= matrix.length-1, right=matrix[0].length-1, i=0 ,j=0;
List l =new ArrayList<Integer>();
while(true) {
i = up;j =left;
while (j <= right )
l.add(matrix[i][j++]);
up++;
if(up>down)break;
i = up;j=right;
while (i <= down )
l.add(matrix[i++][j]);
right--;
if(right<left)break;
i = down;j=right;
while (j >= left)
l.add(matrix[i][j--]);
down--;
if(up>down)break;
i = down;j=left;
while (i >= up)
l.add(matrix[i--][j]);
left++;
if (left>right)break;
}
return l;
}
}