#include <iostream>
using namespace std;

int main() {
    int N;
    cin >> N;
    
    int num = 1;
    int arr[20][20];
    int row = 0, col = 0;
    int direction = 0; // 0: right, 1: down, 2: left, 3: up
    
    while (num <= N * N) {
        arr[row][col] = num;
        num++;
        
        if (direction == 0) {
            if (col == N - 1 || arr[row][col + 1] != 0) {
                direction = 1;
                row++;
            } else {
                col++;
            }
        } else if (direction == 1) {
            if (row == N - 1 || arr[row + 1][col] != 0) {
                direction = 2;
                col--;
            } else {
                row++;
            }
        } else if (direction == 2) {
            if (col == 0 || arr[row][col - 1] != 0) {
                direction = 3;
                row--;
            } else {
                col--;
            }
        } else if (direction == 3) {
            if (row == 0 || arr[row - 1][col] != 0) {
                direction = 0;
                col++;
            } else {
                row--;
            }
        }
    }
    
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    
    return 0;
}
``
题目描述:经过上次猪猪们的偷袭小鸟们也改变了小石头的存放方式将1~NxN之间的自然数按下图所示的次序依次存放到一个NxN的二维数组中。下图描述了N=5时各个元素的值及其赋值次序输出时只要输出各个元素的值。	1 2 9 10 25 	4 3 8 11 24	5 6 7 12 23 	16 15 14 13 22 	17 18 19 20 21 输入一个正整数NN<=20。输出:输出上图所示的数字方阵

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

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