Skip to content

Instantly share code, notes, and snippets.

@icameling
Last active July 18, 2022 08:06
Show Gist options
  • Save icameling/a9dbb9a816c94c860e65b2413b6554ca to your computer and use it in GitHub Desktop.
Save icameling/a9dbb9a816c94c860e65b2413b6554ca to your computer and use it in GitHub Desktop.
#数组 #螺旋矩阵 #leetcode
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
// 行 列
vector<vector<int>> mat;
for (int i = 0; i < n; ++i) {
vector<int> tmp;
for (int j = 0; j < n; ++j)
tmp.push_back(0);
mat.push_back(tmp);
}
assert(mat.size() == n && "mat size not equal to n");
// right down left up
int step[4][2] = {{0,1}, {1,0}, {0, -1}, {-1,0}};
int size = n * n;
int num = 1;
int row = 0, col = 0;
int k_step = 0;
while (num <= size) {
mat.at(row).at(col) = num++;
int next_row = row + step[k_step][0];
int next_col = col + step[k_step][1];
if (next_row < 0 || next_row >= n || next_col < 0 || next_col >= n)
k_step = (k_step + 1) % 4;
else if (mat.at(next_row).at(next_col) != 0)
k_step = (k_step + 1) % 4;
// update
row = row + step[k_step][0];
col = col + step[k_step][1];
}
return mat;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment