n行n列顺时针螺旋方阵c++
时间: 2023-07-19 15:29:19 浏览: 105
使用C++实现的螺旋方阵
下面是一个实现 n 行 n 列顺时针螺旋方阵的 C++ 代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> spiralOrder(int n) {
vector<vector<int>> res(n, vector<int>(n));
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int num = 1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) {
res[top][j] = num++;
}
top++;
for (int i = top; i <= bottom; i++) {
res[i][right] = num++;
}
right--;
if (top <= bottom) {
for (int j = right; j >= left; j--) {
res[bottom][j] = num++;
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
res[i][left] = num++;
}
left++;
}
}
return res;
}
int main() {
int n = 4;
vector<vector<int>> res = spiralOrder(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << res[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
该算法使用了四个指针来控制螺旋方阵的遍历顺序,具体实现可以参考代码注释。
阅读全文