返回题解分享
讨论 / 题解分享/ 帖子详情

蛇形填数2 - 题解

#include <bits/stdc++.h>

using namespace std;



const int N = 1010;

int a[N][N];



int main() {

    int m, n;

    cin >> m >> n;

	//初始位置为右上角

    int y = n;

    int x = 1;


    int cnt = 1;



    while (cnt <= m \* n) {


        // 下

        while (x <= m && a[x][y] == 0) {

            a[x][y] = cnt++;

            x++;

        }

        x--;//这里x--是因为最后下走的时候x多加了一次 下面同理

        y--;



        // 左

        while (y >= 1 && a[x][y] == 0) {

            a[x][y] = cnt++;

            y--;

        }

        y++;

        x--;



        // 上

        while (x >= 1 && a[x][y] == 0) {

            a[x][y] = cnt++;

            x--;

        }

        x++;

        y++;



        // 右

        while (y <= n && a[x][y] == 0) {

            a[x][y] = cnt++;

            y++;

        }

        y--;

        x++;

    }



    // 输出

    for(int i = 1;i <= m;i++)

    {	

    	for(int j = 1;j <= n;j++)

    	{

    		cout << setw(5) << a[i][j];	

    	}

    	cout << '\\n';

    }

    return 0;

}
0 回复 0 转发 0 喜欢 1 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!