问题描述:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
与spiral matrix I 类似
代码如下:
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
//init result
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
result[i][j] = 0;
int index = 0;
int num = n*n;
int row = 0,col = -1;
while(index<num){
for(col = col+1;col<n;col++){
if(result[row][col]!=0)
break;
result[row][col] = ++index;
}
col--;
for(row = row+1;row<n;row++){
if(result[row][col]!=0)
break;
result[row][col] = ++index;
}
row--;
for(col = col-1;col>=0;col--){
if(result[row][col] != 0)
break;
result[row][col] = ++index;
}
col++;
for(row = row-1;row>=0;row--){
if(result[row][col] != 0)
break;
result[row][col] = ++index;
}
row++;
}
return result;
}