You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
28 lines
847 B
28 lines
847 B
#include <bits/stdc++.h>
|
|
|
|
using namespace std;
|
|
const int N = 10;
|
|
int a[N][N];
|
|
int dx[] = {0, 1, 0, -1};
|
|
int dy[] = {1, 0, -1, 0};
|
|
int n;
|
|
int main() {
|
|
cin >> n;
|
|
//出发点
|
|
int x = 0, y = 0;
|
|
a[0][0] = 1;
|
|
int dir = 0; //方向
|
|
for (int i = 2; i <= n * n; i++) {
|
|
//下一个位置,优先尝试当前方向的下一个位置,也可能不行
|
|
int nx = x + dx[dir], ny = y + dy[dir];//下一个位置不能出界,不能走过
|
|
if (nx == n || nx < 0 || ny == n || ny < 0 || a[nx][ny])
|
|
dir = (dir + 1) % 4;//终于找对了前进方向,走之~
|
|
x += dx[dir], y += dy[dir], a[x][y] = i;
|
|
}//输出结果
|
|
for (int i = 0; i < n; i++) {
|
|
for (int j = 0; j < n; j++)
|
|
printf("%3d", a[i][j]);
|
|
printf("\n");
|
|
}
|
|
return 0;
|
|
} |