Property Distribution

題目鏈接:https://vjudge.net/problem/Aizu-0118

Description

在H * W的矩形果園里有蘋果、梨、蜜柑三種果樹, 相鄰(上下左右)的同種果樹屬于同一個(gè)區(qū)域,給出果園的果樹分布,求總共有多少個(gè)區(qū)域。

Input

多組數(shù)據(jù),每組數(shù)據(jù)第一行為兩個(gè)整數(shù)H、W(H <= 100, W <= 100), H =0 且 W = 0代表輸入結(jié)束。以下H行W列表示果園的果樹分布, 蘋果是@,梨是#, 蜜柑是*。

Output

對(duì)于每組數(shù)據(jù),輸出其區(qū)域的個(gè)數(shù)。

Sample Input

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

Sample Output

33

題解:

#include <iostream>
using namespace std;
#define MAX 101
char map[MAX][MAX];
int W, H;
int x0, y0;
char temp;
int num;
int dir[4][2] = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}};
void dfs(int x, int y)
{
    temp = map[x][y];
    map[x][y] = '.';
    for (int k = 0; k < 4; k++)
    {
        int nx = x + dir[k][0];
        int ny = y + dir[k][1];
        if (map[nx][ny] == temp && nx < H && 0 <= nx && ny < W && ny >= 0)
            dfs(nx, ny);
    }
    return;
}
int main()
{
    while (cin >> H >> W)
    {
        if (W == 0 && H == 0)
            break;
        num = 0;
        for (int i = 0; i < H; i++)
            for (int j = 0; j < W; j++)
                cin >> map[i][j];
        for (int i = 0; i < H; i++)
            for (int j = 0; j < W; j++)
            {
                if (map[i][j] != '.')
                {
                    dfs(i, j);
                    num++;
                }
            }
        cout << num << endl;
    }
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容