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

蛇形填数2 - 题解

从1位置起始,到头就改变方向,直至数字达到n*m停止

#include <bits/stdc++.h>
using namespace std;

const int N = 110;
int mp[N][N];

int main() {
    int n, m;
    scanf("%d %d", &n, &m);

    int posx = 1, posy = m;
    int num = 1;
    int direction = 1;

    while (num <= n * m) {
        mp[posx][posy] = num++;
        if (direction == 1) {
            if (posy < m && !mp[posx][posy + 1]) posy++;
            else {
                direction = 2;
                posx++;
            }
        } else if (direction == 2) {
            if (posx < n && !mp[posx + 1][posy]) posx++;
            else {
                direction = 3;
                posy--;
            }
        } else if (direction == 3) {
            if (posy > 1 && !mp[posx][posy - 1]) posy--;
            else {
                direction = 4;
                posx--;
            }
        } else {
            if (posx > 1 && !mp[posx - 1][posy]) posx--;
            else {
                direction = 1;
                posy++;
            }
        }
    }

    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            printf("%5d", mp[i][j]);
        }
        printf("\n");
    }

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