转圈过程(边界处理)遵循循环不变量的原则,坚持一个原则处理每一条边,左闭右开处理
cpp
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> num(n, vector<int>(n, 0));
int startx = 0;
int starty = 0;
int offset = 1;
int count = 1;
int loop = n/2;
int i;
int j;
while(loop --)
{
for( j = starty; j < n - offset; j++)
{
num[startx][j] = count;
count ++;
}
for( i = startx; i < n - offset; i++)
{
num[i][j] = count;
count ++;
}
for( ; j > starty; j--)
{
num[i][j] = count;
count ++;
}
for( ; i > startx; i--)
{
num[i][j] = count;
count ++;
}
startx++;
starty++;
offset++;
}
if(n % 2)
{
num[n/2][n/2] = count;
}
return num;
}
};