经典蛇形矩阵 洛谷 P5731
#include<iostream> #include<cmath> using namespace std; const int N = 11; int f[N][N]; int main() { int n; cin >> n; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; int x = 1, y = 1,d = 0; for (int i = 1;i <= n * n;i ++) { f[x][y] = i; int a = x + dx[d]; int b = y + dy[d]; if (a > n || a < 1 || b > n || b < 1 || f[a][b]) { d = (d + 1) % 4; a = x + dx[d]; b = y + dy[d]; } x = a; y = b; } for (int i = 1;i <= n;i ++) { for (int j = 1;j <= n;j ++) printf("%3d",f[i][j]); cout << endl; } return 0; }
https://www.luogu.com.cn/problem/P5731