一、题目
二、代码
class Solution
{
public int[][] generateMatrix(int n)
{
int [][]res = new int[n][n];
int direction =0;//0右 1下 2左 3上
int max_length = n*n;
int x = 0 ;
int y = 0 ;
int i = 0;
for( i = 1 ;i<=max_length;i++)
{
System.out.println("x" + x +" y " + y);
if(direction==0)
{
res[x][y] = i;
if(y+1!=n&&res[x][y+1]==0)
{
x=x;
y=y+1;
}
else
{
direction = 1;
x=x+1;
y=y;
}
}
else if (direction == 1)
{
res[x][y]=i;
if(x+1!=n && res[x+1][y]==0)
{
x=x+1;
y=y;
}
else
{
direction=2;
x=x;
y=y-1;
}
}
else if(direction == 2)
{
res[x][y] = i;
if(y-1!=-1&&res[x][y-1]==0)
{
x=x;
y=y-1;
}
else
{
direction = 3;
x=x-1;
y=y;
}
}
else
{
res[x][y] = i;
if(x-1!=-1 && res[x-1][y]==0)
{
x=x-1;
y=y;
}
else
{
direction=0;
x=x;
y=y+1;
}
}
}
return res;
}
}
}
三、运行结果
四、附录
二刷
class Solution
{
public int[][] generateMatrix(int n)
{
int[][] result = new int[n][n];
int col = 0;
int row = 0;
int direction = 1;
int i =0;
int final_num = n*n;
for(i=1;i<=final_num;i++)
{
result[row][col] = i;
if(direction==1 )
{
if(col+1>=n||result[row][col+1] !=0)
{
direction =2;
row = row+1;
}
else
{
col = col+1;
}
}
else if(direction==2 )
{
if(row+1>=n||result[row+1][col] !=0)
{
direction =3;
col = col - 1;
}
else
{
row = row+1;
}
}
else if(direction==3 )
{
if(col-1<0 || result[row][col-1] !=0)
{
direction =4;
row = row - 1;
}
else
{
col = col - 1;
}
}
else if(direction == 4)
{
if(row-1<0 || result[row-1][col] !=0)
{
direction =1;
col = col + 1;
}
else
{
row = row - 1;
}
}
}
return result;
}
}