'commit'
This commit is contained in:
28
TangDou/LuoGuBook/P5731.cpp
Normal file
28
TangDou/LuoGuBook/P5731.cpp
Normal file
@@ -0,0 +1,28 @@
|
||||
#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;
|
||||
}
|
||||
Reference in New Issue
Block a user