#include <iostream>
#include <vector>

using namespace std;

vector<vector<int>> generateSnakeMatrix(int n) {
    vector<vector<int>> matrix(n, vector<int>(n));
    int num = 1;
    int row = 0, col = 0;
    int direction = 0; // 0: right, 1: down, 2: left, 3: up
    
    while (num <= n * n) {
        matrix[row][col] = num;
        num++;
        
        switch (direction) {
            case 0: // right
                if (col < n - 1 && matrix[row][col + 1] == 0) {
                    col++;
                } else {
                    direction = 1; // change direction to down
                    row++;
                }
                break;
            case 1: // down
                if (row < n - 1 && matrix[row + 1][col] == 0) {
                    row++;
                } else {
                    direction = 2; // change direction to left
                    col--;
                }
                break;
            case 2: // left
                if (col > 0 && matrix[row][col - 1] == 0) {
                    col--;
                } else {
                    direction = 3; // change direction to up
                    row--;
                }
                break;
            case 3: // up
                if (row > 0 && matrix[row - 1][col] == 0) {
                    row--;
                } else {
                    direction = 0; // change direction to right
                    col++;
                }
                break;
        }
    }
    
    return matrix;
}

int main() {
    int n;
    cin >> n;
    
    vector<vector<int>> matrix = generateSnakeMatrix(n);
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cout.width(5);
            cout << matrix[i][j];
        }
        cout << endl;
    }
    
    return 0;
}
``
描述输入一个正整数 n 生成一个 nn 的蛇形方阵具体见样例。输入描述一行一个正整数 n 。输出描述共 n 行每行一个正整数每个正整数占5列。用例输入 1 5用例输出 1 15 7 6 2 1 16 14 8 5 3 22 17 13 9 4 23 21 18 12 10 25 24 2

原文地址: https://www.cveoy.top/t/topic/iFOr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录