力扣https://leetcode-cn.com/problems/spiral-matrix/难度中等893
给你一个 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
class Solution {
public List spiralOrder(int[][] matrix) {
List ans = new ArrayList();
int line = matrix.length;
int row = matrix[0].length;
int temp = line*row;
int i=0,j=0;
int x=0;
while(temp>0)
{
//向右
while(j+10)
{
ans.add(matrix[i][j]);
System.out.print(matrix[i][j]+" A ");
j++;
temp--;
}
System.out.println();
//向下
while(i0)
{
ans.add(matrix[i][j]);
System.out.print(matrix[i][j]+" B ");
i++;
temp--;
}
System.out.println();
//向左
i--;
while(j>x && temp>0)
{
j--;
ans.add(matrix[i][j]);
System.out.print(matrix[i][j]+" C ");
temp--;
}
System.out.println();
//向上
while(i>x+1 && temp>0)
{
i--;
ans.add(matrix[i][j]);
System.out.print(matrix[i][j]+" D ");
temp--;
}
i--;
j++;
i++;
row--;
line--;
x++;
}
return ans;
}
}