1 条题解

  • 0
    @ 2025-8-24 22:13:51

    自动搬运

    查看原文

    来自洛谷,原作者为

    avatar volatile
    等下次能改名字了,而且橙名了,我就把名字给改掉,看你们还认不认得出我

    搬运于2025-08-24 22:13:51,当前版本为作者最后更新于2025-06-01 12:15:00,作者可能在搬运后再次修改,您可在原文处查看最新版

    自动搬运只会搬运当前题目点赞数最高的题解,您可前往洛谷题解查看更多

    以下是正文


    思路

    因为大小为 n×nn\times{n},所以最大的数就是 n2n^2,用一个 nownow 变量枚举 11n2n^2。从四个方向遍历一个二维数组 aa。若当前位置为 ax,ya_{x,y}

    1. 向右遍历
    while (y + 1 <= n && a[x][y + 1] == 0) {
        y++;
        a[x][y] = now;
        now++;
    }
    

    只要当前位置不是空的,就可以填入,否则换向。

    1. 向下遍历
    while (x + 1 <= n && a[x + 1][y] == 0) {
        x++;
        a[x][y] = now;
        now++;
    }
    
    1. 向左遍历
    while (y - 1 >= 1 && a[x][y - 1] == 0) {
        y--;
        a[x][y] = now;
        now++;
    }
    
    1. 向上遍历
    while (x - 1 >= 1 && a[x - 1][y] == 0) {
        x--;
        a[x][y] = now;
        now++;
    }
    

    最后输出,注意右对齐 33 格,可以用 printf("%3d", a[i][j]); 实现。

    代码

    #include<iostream>
    #include<cstdio>
    using namespace std;
    int a[20][20];
    int main()
    {
    	int n;
    	int now = 2, x = 1, y = 1;
    	a[1][1] = 1;
    	cin >> n;
    	while (now <= n * n) {
    		while (y + 1 <= n && a[x][y + 1] == 0) {
    			y++;
    			a[x][y] = now;
    			now++;
    		}
    		while (x + 1 <= n && a[x + 1][y] == 0) {
    			x++;
    			a[x][y] = now;
    			now++;
    		}
    		while (y - 1 >= 1 && a[x][y - 1] == 0) {
    			y--;
    			a[x][y] = now;
    			now++;
    		}
    		while (x - 1 >= 1 && a[x - 1][y] == 0) {
    			x--;
    			a[x][y] = now;
    			now++;
    		}
    	}
    	for (int i = 1; i <= n; i++) {
    		for (int j = 1; j <= n; j++) {
    			printf("%3d", a[i][j]);
    		}
    		cout << endl;
    	}
    	return 0;
    }
    
    • 1

    信息

    ID
    4709
    时间
    1000ms
    内存
    125MiB
    难度
    1
    标签
    (无)
    递交数
    0
    已通过
    0
    上传者