挑战程序设计竞赛 2.1章习题 AOJ 0118 Property Distribution dfs bfs

地址 https://vjudge.net/problem/Aizu-0118

原文是日志 大概题意是 H*W的果园种满了苹果、梨、蜜柑三种果树,如果把上下左右看成是连接状态那么请问果园可以划分成几个区域

输入

多组数据

第一行输入两个数值 H W 代表果园的长和宽

然后输入H行W列的char数组 代表苹果、梨、蜜柑(@ # * 表示 )

0 0 表示输入结束

输出

每行输出一个答案 表示果园可以划分成多少个相同水果区域 


Sample Input
10 10
####*****@
@#@@@@#*#*
@##***@@@*
#****#*@**
##@*#@@*##
*@@@@*@@@#
***#@*@##*
*@@@*@@##@
*@*#*@##**
@****#@@#@
0 0
Output for the Sample Input
33

解法 

DFS BFS 并查集均可

类似 

poj 1979 Red and Black 题解《挑战程序设计竞赛》

 

代码如下 可当作dfs模板

// 11235.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>

using namespace std;

const int N = 110;

char arr[N][N];

int H, W;
int cnt = 0;
int addx[4] = { 1,-1,0,0 };
int addy[4] = { 0,0,1,-1 };


void dfs( int x, int y,char p)
{
    arr[x][y] = '0';
    for (int i = 0; i < 4; i++) {
        int newx = x + addx[i];
        int newy = y + addy[i];
        if (newx >= 0 && newx < H && newy >= 0 && newy < W && arr[newx][newy] == p) {
            dfs(newx, newy, p);
        }
    }

}


int main()
{
    while (cin >> H >> W, W != 0) {
        for (int i = 0; i < H; i++) {
            for (int j = 0; j < W; j++) {
                cin >> arr[i][j];
            }
        }
        cnt = 0;
        for (int i = 0; i < H; i++) {
            for (int j = 0; j < W; j++) {
                if (arr[i][j] != '0') {
                    cnt++;
                    dfs(i, j, arr[i][j]);
                }
            }
        }

        cout << cnt << endl;
  }

    return 0;
}

 

posted on 2021-01-12 19:17  itdef  阅读(154)  评论(0编辑  收藏  举报

导航