代码拉取完成,页面将自动刷新
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int val = 1;
vector<vector<int>> matrix(n, vector<int>(n));
int rUpper = 0, rDowner = n - 1;
int cLeft = 0, cRight = n - 1;
int r = 0, c = 0;
enum {
RIGHT,
DOWN,
LEFT,
UP
} direct;
direct = RIGHT;
while (val <= n * n) {
matrix[r][c] = val;
switch(direct) {
case RIGHT:
if (c == cRight) {
r++;
direct = DOWN;
rUpper++;
}
else
c++;
break;
case DOWN:
if (r == rDowner) {
c--;
direct = LEFT;
cRight--;
}
else
r++;
break;
case LEFT:
if (c == cLeft) {
r--;
direct = UP;
rDowner--;
}
else
c--;
break;
case UP:
if (r == rUpper) {
c++;
direct = RIGHT;
cLeft++;
}
else
r--;
break;
default:
break;
}
val++;
}
return matrix;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。