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 ]
]
题意,给我们一个n,求解出n*n的矩阵,同时填充数字,循环填充。
代码:
public int[][] generateMatrix(int n) {
int total = n*n;
int[][] result= new int[n][n];
int x=0;
int y=0;
int step = 0;
for(int i=0;i=0+step){
i++;
result[x][y]=i;
y--;
}
y++;
x--;
step++;
while(x>=0+step){
i++;
result[x][y]=i;
x--;
}
x++;
y++;
}
return result;
}