20ptsWA求助
查看原帖
20ptsWA求助
784117
chentianyi0109楼主2023/9/10 08:50
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 10;
int n;
int a[N][N];
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int dir;
bool check (int x, int y) {
	if (x < 1 || x > n || y < 1 || y > n) return 0;
	if (a[x][y]) return 0;
	return 1;
}
void work (int &x, int &y, int &id) {
	a[x][y] = id ++;
	int tx = x + dx[dir];
	int ty = y + dy[dir];
	if (check (tx, ty)) {
		x = tx;
		y = ty;
	} 
	else {
		dir = (dir + 1) % 4;
		x = x + dx[dir];
		y = y + dy[dir];
	}
}
signed main () {
	cin >> n;
	int x = 1, y = 1, id = 1;
	for (int i = 1; i <= n * n; i ++) {
		work (x, y, id);
	}
	for (int i = 1; i <= n; i ++) {
		for (int j = 1; j <= n; j ++) {
			printf ("%3d%c", a[i][j], j == n ? '\n' : ' ');
		}
	}
} 
2023/9/10 08:50
加载中...