題目鏈接: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;
}