Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
给一个整数,输出旋转矩阵。
public class Solution {
public int[][] generateMatrix(int n) {
if(n<0){
return null;
}
int[][] ans = new int[n][n];
MatrixHelp2(ans,1,0,0,n);
return ans;
}
public void MatrixHelp2(int[][] ans,int key,int starti,int startj,int n){
if(n==0){
return;
}
if(n==1){
ans[starti][startj]=key;
return;
}
for(int j=startj;j<startj+n-1;j++){
ans[starti][j]=key++;
}
for(int i=starti;i<starti+n-1;i++){
ans[i][startj+n-1]=key++;
}
for(int j=startj+n-1;j>startj;j--){
ans[starti+n-1][j]=key++;
}
for(int i=starti+n-1;i>starti;i--){
ans[i][startj]=key++;
}
MatrixHelp2(ans,key,starti+1,startj+1,n-2);
}
}
另外,还有非递归写法,在大牛的博客里面有: