题解 | #回型矩阵#
回型矩阵
https://ac.nowcoder.com/acm/problem/22230
using namespace std;
int main()
{
int a[100][100] = { 0 };
int n; cin >> n; int pos = 6;
int edge = n;
// pos=4向说明向右走,6向右,2向下,8向上
a[1][1] = 1; int i = 1; int j = 1;
for (int k = 2; k <= n * n; k++)
{
//如果遇到右墙壁,pos=4;
if (j == edge && pos == 6)
{
a[++i][j] = k;
pos = 2;
}
//如果在中间,pos=6;
// 如果遇到下墙壁,pos=2;
else if (i == edge && pos == 2)
{
a[i][--j] = k;
pos = 4;
}
else if (j == n - edge + 1 && pos == 4)
{
a[--i][j] = k;
pos = 8;
}
else if (i == n - edge + 2 && pos == 8)
{
a[i][++j] = k;
pos = 6;
edge = edge - 1;
}
else if (pos == 6)
{
a[i][++j] = k;
}
else if (pos == 2)
{
a[++i][j] = k;
}
else if (pos == 4)
{
a[i][--j] = k;
}
else if (pos == 8)
{
a[--i][j] = k;
}
}
for (int i= 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}