跳到正文

个人记录

U722108答案

Taptab约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年8月25日
收录
2026年8月25日
更新
2026年11月14日
篇幅
约 2 分钟
获赞
1

版本

  1. v1当前
C++
#include <iostream>
#include <vector>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int N;
    cin >> N;
    vector<vector<int>> mat(N, vector<int>(N, 0));

    // 方向:下、左、上、右
    int dr[4] = {1, 0, -1, 0};
    int dc[4] = {0, -1, 0, 1};

    int r = 0, c = N - 1, d = 0;  // 右上角起点,先向下
    for (int val = 1; val <= N * N; ++val) {
        mat[r][c] = val;
        int nr = r + dr[d], nc = c + dc[d];
        if (nr < 0 || nr >= N || nc < 0 || nc >= N || mat[nr][nc] != 0) {
            d = (d + 1) % 4;
            nr = r + dr[d], nc = c + dc[d];
        }
        r = nr, c = nc;
    }

    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            cout << mat[i][j] << (j == N - 1 ? "\n" : " ");
        }
    }
    return 0;
}
原文