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

题意

原题是这样的:

AOJ 0118 Property Distribution {深度优先搜索}_第1张图片

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

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

AOJ 0118 Property Distribution {深度优先搜索}_第2张图片

它的输入是这样的:

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

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

分析

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

AOJ 0118 Property Distribution {深度优先搜索}_第3张图片

走过的点,全部都赋值为 ! ,保证下次不会走到就好。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);
        }
    }
}

你可能感兴趣的:(算法,广度优先搜索,广搜,深搜,AOJ)