AOJ 0118 Property Distribution {深度优先搜索}

题意

原题是这样的:

这里写图片描述

原题呢就是上面这个,我还是来简单翻译一下吧。

看到下面的图了么?大概有3种图案的标志,相同的可以拼接到一起,你需要找出最后一共有多少块。比如这里的就是有10块。

这里写图片描述

它的输入是这样的:

10 10
####*****@
@#@@@@#*#*
@##***@@@*
#****#*@**
##@*#@@*##
*@@@@*@@@#
***#@*@##*
*@@@*@@##@
*@*#*@##**
@****#@@#@
0 0

两个0表示结束输入,输出块的个数即可,上面的输入对应的输出就是33。

分析

我还是用的这个给代码定的规定,方向什么的。

这里写图片描述

走过的点,全部都赋值为 !,保证下次不会走到就好。for循环中进行判断,每走一次就完成计算一块,step也跟着加1,最后输出其和即可。

代码

#include <iostream>
using namespace std;

#define MAX_W 100
#define MAX_H 100

char room[MAX_W][MAX_H];
int W,H;

const int direc[4][2] = {
    {0, -1},
    {1, 0},
    {0, 1},
    {-1, 0},
};

void dfs(const int& row, const int& col, const char c);

int main() {
    while(cin>>H>>W, W > 0) {
        int step = 0;
        int col, row;
        for (row = 0; row < H; ++row) {
            for (col = 0; col < W; ++col) {
                cin >> room[row][col];
            }
        }
        for (row = 0; row < H; ++ row) {
            for(col = 0; col < W; ++ col) {
                if(room[row][col] != '!') {
                    dfs(row, col, room[row][col]);
                    ++ step;
                }
            }
        }
        cout<<step<<endl;
    }
    return 0;
}

void dfs(const int& row, const int& col, const char c) {
    room[row][col] = '!';
    for(int d = 0; d < 4; ++ d) {
        int curRow = row + direc[d][1];
        int curCol = col + direc[d][0];
        if(curRow >= 0 && curRow < H && curCol >= 0 && curCol < W && room[curRow][curCol] == c) {
            dfs(curRow, curCol, c);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值