题解 | #回型矩阵#
回型矩阵
https://www.nowcoder.com/practice/36d5dfddc22c4f5b88a5b2a9de7db343
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int row = 0;
int col = 0;
int top_bound = 0;
int left_bound = 0;
int right_bound = n - 1;
int bottom_bound = n - 1;
int a[n][n];
int i = 1;
int direction = 0;
while (1)
{
if (direction == 0)
{
if (col == right_bound)
{
direction = 1;
top_bound++;
}
else
{
a[row][col] = i;
i++;
col++;
}
}
if (direction == 1)
{
if (row == bottom_bound)
{
direction = 2;
right_bound--;
}
else
{
a[row][col] = i;
i++;
row++;
}
}
if (direction == 2)
{
if (col == left_bound)
{
direction = 3;
bottom_bound--;
}
else
{
a[row][col] = i;
i++;
col--;
}
}
if (direction == 3)
{
if (row == top_bound)
{
direction = 0;
left_bound++;
}
else
{
a[row][col] = i;
i++;
row--;
}
}
if (i == n * n + 1)
break;
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
cout << a[i][j] << " ";
}
cout << endl;
}
}
// 64 位输出请用 printf("%lld")
模拟数组,很经典的题目,按照贪吃蛇的写法写很清楚。
C++题解 文章被收录于专栏
记录在牛客网用C++刷题的题解思路
