← 返回题目页

A1367 蛇形填数1

标程

#include <bits/stdc++.h>
using namespace std;

// 蛇形填数1(A1367):按「一直走,前方走不通就右转」的规则填螺旋方阵
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;
    vector<vector<int>> a(n, vector<int>(n, 0));

    const int dx[4] = {0, 1, 0, -1}; // 右、下、左、上
    const int dy[4] = {1, 0, -1, 0};
    int x = 0, y = 0, dir = 0;        // 初始位置 (1,1),方向向右

    for (int v = 1; v <= n * n; v++) {
        a[x][y] = v; // 把当前数字填进当前格子
        int nx = x + dx[dir], ny = y + dy[dir];
        if (nx < 0 || nx >= n || ny < 0 || ny >= n || a[nx][ny] != 0) {
            dir = (dir + 1) % 4; // 前方走不通,右转 90 度
            nx = x + dx[dir];
            ny = y + dy[dir];
        }
        x = nx;
        y = ny;
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%5d ", a[i][j]); // 每个数占 5 列,右对齐
        }
        printf("\n");
    }
    return 0;
}

动画演示