UVaOJ 657 - The die is cast

——by A Code Rabbit


Description

一道模式识别题。

输入一张像素图,图上有几个骰子。

要求识别图上的骰子的点数。

并且从小到大排序输出。

但是要注意:

  • 两点之间,上下左右相邻的才算靠在一起,如果是斜角相邻则算分开的两个点。


Types

Date Structure :: Graphs


Analysis

求一张无向图的连通分支数,可以得知有几个骰子。

然后把骰子作为一张子图再求其连通分支数,就可以知道骰子上的点数。

可以用 DFS 来求连通分支数,则二重的 DFS 即可 AC 。


Solution

// UVaOJ 657
// The die is cast
// by A Code Rabbit

#include <algorithm>
#include <cstdio>

using namespace std;

const int LIMITS_W = 100;
const int LIMITS_H = 100;

struct Change {
    int x;
    int y;
};

Change change[] = {{-1, 0}, {1, 0},
                   {0, -1}, {0, 1}};

int num_case = 0;

char picture[LIMITS_W][LIMITS_H];
int w, h;

int dots[LIMITS_W * LIMITS_H];
int top;

int FloodFillDie(int x, int y);
bool FloodFillDot(int x, int y);

int main() {
    while (scanf("%d%d", &w, &h)) {
        getchar();
        // Exit.
        if (!w && !h) {
            break;
        }
        // Inputs.
        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                scanf("%c", &picture[i][j]);
            }
            getchar();
        }
        // DFS.
        top = 0;
        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                int result = FloodFillDie(i, j);
                if (result) {
                    dots[top++] = result;
                }
            }
        }
        // Sort.
        sort(dots, dots + top);
        // Outputs
        printf("Throw %d\n", ++num_case);
        for (int i = 0; i < top - 1; ++i) {
            printf("%d ", dots[i]);
        }
        printf("%d\n", dots[top - 1]);
        printf("\n");
    }

    return 0;
}

int FloodFillDie(int x, int y) {
    if (x < 0 || x >= h
     || y < 0 || y >= w) {
        return 0;
    }
    if (picture[x][y] == '.') {
        return 0;
    }
    int sum = FloodFillDot(x, y) ? 1 : 0;
    picture[x][y] = '.';
    for (int i = 0; i < 4; ++i) {
        sum += FloodFillDie(x + change[i].x, y + change[i].y);
    }
    return sum;
}

bool FloodFillDot(int x, int y) {
    if (x < 0 || x >= h
     || y < 0 || y >= w) {
        return false;
    }
    if (picture[x][y] != 'X') {
        return false;
    }
    picture[x][y] = '*';
    for (int i = 0; i < 4; ++i) {
        FloodFillDot(x + change[i].x, y + change[i].y);
    }
    return true;
}


下载PDF

参考资料:无

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值