题解 | #回型矩阵#
回型矩阵
https://www.nowcoder.com/practice/36d5dfddc22c4f5b88a5b2a9de7db343
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int n;
cin >> n;
int a[n][n]; // 初始化一个 n x n 的矩阵,所有元素初始化为 0
int num = 1; // 从1开始填充矩阵
int top = 0, bottom = n-1, left = 0, right = n-1;//定义矩阵边界,后面需要移动边界
// 当 top <= bottom 并且 left <= right 时,不断填充矩阵
while (top <= bottom && left <= right) {
// 从左到右填充顶边
for (int i = left; i <= right; ++i) {
a[top][i] = num++;
}
top++; // 顶边向下移动
// 从上到下填充右边
for (int i = top; i <= bottom; ++i) {
a[i][right] = num++;
}
right--; // 右边向左移动
// 检查是否还有行需要填充
if (top <= bottom) {
// 从右到左填充底边
for (int i = right; i >= left; --i) {
a[bottom][i] = num++;
}
bottom--; // 底边向上移动
}
// 检查是否还有列需要填充
if (left <= right) {
// 从下到上填充左边
for (int i = bottom; i >= top; --i) {
a[i][left] = num++;
}
left++; // 左边向右移动
}
}
// 输出填充好的矩阵
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}
