题目描述:
注意事项:如果是一个方阵,可以直接定义遍历的圈数,并且如果是奇数的话,需要对圆圈中间的数做填充所补充;
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
int loop = n/2;
int startx = 0, starty = 0;
int i,j, offset = 1, count = 1;
while (loop--) {
i = startx;
j = starty;
for (j = starty; j < n - offset; j++) {
matrix[i][j] = count;
count += 1;
}
for (i = startx; i < n - offset; i++) {
matrix[i][j] = count;
count += 1;
}
for (; j > starty; j--) {
matrix[i][j] = count;
count += 1;
}
for (; i > startx; i--) {
matrix[i][j] = count;
count += 1;
}
offset += 1;
startx++;
starty++;
}
if (n%2 == 1) matrix[n/2][n/2] = count;
return matrix;
}
链接:https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/description/
题目描述:
注意事项:
- 如果是方阵,不能通过圈数来作为循环停止的标志;
- 根据循环停止的条件,最后一行或者最后一列是不能被遍历到,需要单独处理;
vector<int> spiralArray(vector<vector<int>>& array) {
vector<int> result;
if (array.size() == 0) return result;
int top = 0, bottom = array.size() - 1;
int left = 0, right = array[0].size() - 1;
while (left < right && top < bottom) {
for (int i = left; i < right; i++) result.push_back(array[top][i]);
for (int i = top; i < bottom; i++) result.push_back(array[i][right]);
for (int i = right; i > left; i--) result.push_back(array[bottom][i]);
for (int i = bottom; i > top; i--) result.push_back(array[i][left]);
top++;
right--;
bottom--;
left++;
}
if (left == right) {
for (int i = top; i <= bottom; i++) result.push_back(array[i][left]);
}else if (top == bottom) {
for (int i = left; i <= right; i++) result.push_back(array[top][i]);
}
return result;
}