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 ] ]
同54.Spiral Matrix类似,都要一层一层的对矩阵进行操作,需要注意的是要判断有多少层:int half = n%2==0?n/2:n/2+1;
每层中都要对上-右-下-左 四个方向进行填充,注意边界条件,避免操作覆盖:
class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
//if(n==0)
int half = n%2==0?n/2:n/2+1;
int count = 1;
while(count<=n*n)
{
for(int i=0;i<half;i++)
{
for(int j=i;j<n-i;j++)
{
result[i][j] = count;
count++;
}
for(int j=i+1;j<n-i;j++)
{
result[j][n-1-i] = count;
count++;
}
for(int j=n-2-i;j>=i;j--)
{
result[n-1-i][j] = count;
count++;
}
for(int j=n-2-i;j>i;j--)
{
result[j][i] = count;
count++;
}
}
}
return result;
}
}