螺旋矩阵II(leetcode 59)
转圈过程(边界处理)遵循循环不变量的原则,坚持一个原则处理每一条边,左闭右开处理
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;
}
};
原文地址:https://blog.csdn.net/m0_74794884/article/details/143838118
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!