Q:题意:在H * W的矩形果园里有苹果、梨、蜜柑三种果树, 相邻(上下左右)的同种果树属于同一个区域,给出果园的果树分布,求总共有多少个区域。
输入:多组数据,每组数据第一行为两个整数H、W(H <= 100, W <= 100), H =0 且 W = 0代表输入结束。以下H行W列表示果园的果树分布, 苹果是@,梨是#, 蜜柑是*。
输出:对于每组数据,输出其区域的个数。
#include<iostream>
#include <stdlib.h>
#define MAX_NUM 110
using namespace std;
int dir[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
void DFS(char arr[][MAX_NUM], int x, int y, int H, int W, char temp) {
if (x >= H || y >= W || x < 0|| y < 0 || arr[x][y] != temp)
{
return ;
}
arr[x][y] = '.';
for (int i = 0; i < 4; i ++)
{
DFS(arr, x + dir[i][0], y + dir[i][1], H, W, temp);
}
}
int main()
{
int H, W;
char arr[MAX_NUM][MAX_NUM];
while (cin >> H >> W && W!=0 && H!=0)
{
for (int i = 0; i < H; i++)
{
for (int j = 0; j < W; j++)
{
cin >> arr[i][j];
}
}
int res = 0;
for (int i = 0; i < H; i++)
{
for (int j = 0; j < W; j++)
{
if (arr[i][j] != '.')
{
DFS(arr, i, j, H, W, arr[i][j]);
res++;
}
}
}
cout << res << endl;
}
return 0;
}
网友评论