代码
public class Solution
{
public int[][] generateMatrix(int n)
{
int[][] res = new int[n][n];
int total = n*n;
int num = 1;
int rowBegin = 0;
int rowEnd = n-1;
int colBegin = 0;
int colEnd = n-1;
while(num <= total)
{
// traverse right (y changes)
for(int y=colBegin; y<=colEnd;y++)
res[rowBegin][y] = num++;
rowBegin++; // move down one row
// traverse down (x changes)
for(int x=rowBegin; x<=rowEnd;x++)
res[x][colEnd] = num++;
colEnd–; // move left one column
// traverse left (y changes)
for(int y=colEnd; y>=colBegin;y–)
res[rowEnd][y] = num++;
rowEnd–; // move up one row
// traverse up (x changes)
for(int x=rowEnd; x>=rowBegin;x–)
res[x][colBegin] = num++;
colBegin++; // move right one column
}
return res;
}
}