螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
示例 2:
思路: 定义left,right,top,bottom四个边界,然后循环,每次循环结束后将边界移动。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if(matrix.length==0)
return new ArrayList<Integer>();
int left=0;//左边界
int right=matrix[0].length-1;//右边界
int top=0;//上边界
int bottom=matrix.length-1;//下边界
int x=0;//用来计数
Integer[] res=new Integer[(right+1)*(bottom+1)];
while(true){
//从left到right
for(int i=left;i<=right;i++) res[x++]=matrix[top][i];
if(++top>bottom) break;
//从top到bottom
for(int i=top;i<=bottom;i++) res[x++]=matrix[i][right];
if(left>--right)break;
//从right到left
for(int i=right;i>=left;i--) res[x++]=matrix[bottom][i];
if(top>--bottom)break;
//从bottom到top
for(int i=bottom;i>=top;i--) res[x++]=matrix[i][left];
if(++left>right)break;
}
return Arrays.asList(res);
}
}
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
class Solution {
public int[][] generateMatrix(int n) {
//初始化边界条件
int left=0;
int top=0;
int right=n-1;
int bottom=n-1;
//初始化n*n大小的矩阵
int[][] res=new int[n][n];
int nums=1;
int tar=n*n;
while(true){
//left to right
for(int i=left;i<=right;i++) res[top][i]=nums++;
if(++top>bottom) break;
//top to bottom
for(int i=top;i<=bottom;i++) res[i][right]=nums++;
if(left>--right)break;
//right to left
for(int i=right;i>=left;i--) res[bottom][i]=nums++;
if(top>--bottom)break;
//bottom to top
for(int i=bottom;i>=top;i--) res[i][left]=nums++;
if(++left>right)break;
}
return res;
}
}

