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 ] ]思路:和上一题Spiral Matrix类似,只不过变成方阵了,数据范围从1到n^2。
class Solution {
public int[][] generateMatrix(int n) {
int[][] x = new int[n][n];
int digit = 1;
int rowstart = 0;
int colstart = 0;
int rowend = n - 1;
int colend = n - 1;
while(colend>=colstart&&rowstart<=rowend){
for(int i = colstart ;i<=colend ; i++){
x[rowstart][i] = digit++;
}
rowstart++;
for(int i = rowstart ;i<=rowend ; i++){
x[i][colend] = digit++;
}
colend--;
if(colend>=colstart){
for(int i = colend ;i>=colstart ; i--){
x[rowend][i] = digit++;
}
}
rowend--;
if(rowstart<=rowend){
for(int i = rowend ;i>=rowstart ; i--){
x[i][colstart] = digit++;
}
}
colstart++;
}
return x;
}
}