输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
1、模拟运算
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix.length==0) return new int[0];
int row=matrix.length;
int col=matrix[0].length;
int num=row*col;
int[] res=new int[num];
boolean[][] flag=new boolean[row][col];
int[][] gowhere={{0,1},{1,0},{0,-1},{-1,0}};
int i=0,j=0;
int index=0;
for(int k=0;k<num;k++){
res[k]=matrix[i][j];
flag[i][j]=true;
int newi=i+gowhere[index][0],newj=j+gowhere[index][1];
if(newj>=col||newi>=row||newj<0||newi<0||flag[newi][newj]==true){
index++;
index%=4;
}
i+=gowhere[index][0];
j+=gowhere[index][1];
}
return res;
}
}
2、边界
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix.length==0) return new int[0];
int row=matrix.length;
int col=matrix[0].length;
int[] res=new int[row*col];
int left=0,top=0,right=col-1,bottom=row-1;
int index=0;
while(left<=right&&top<=bottom){
for(int j=left;j<=right;j++){
res[index++]=matrix[top][j];
}
for(int i=top+1;i<=bottom;i++){
res[index++]=matrix[i][right];
}
if(top<bottom){
for(int j=right-1;j>=left;j--){
res[index++]=matrix[bottom][j];
}
}
if(left<right){
for(int i=bottom-1;i>top;i--){
res[index++]=matrix[i][left];
}
}
left++;
right--;
top++;
bottom--;
}
return res;
}
}