您的位置:首页 > 运维架构

[挑战程序设计竞赛] AOJ 0118 - Property Distribution

2014-11-24 19:33 309 查看
题意:
在H * W的矩形果园里有苹果、梨、蜜柑三种果树, 相邻(上下左右)的同种果树属于同一个区域,求总共有多少个区域。

输入:

多组数据,每组数据第一行为两个整数H,W(H <= 100, W <= 100), H =0 且 W = 0代表输入结束。以下H行W列表示果园的果树分布, 苹果是@,梨是#, 蜜柑是*。

输出:

对于每组数据,输出其区域的个数。
BFS写的比较直观,写的过程把行和列写反了,找了半天。。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <assert.h>
#include <time.h>
typedef long long LL;
const int INF = 500000001;
const double EPS = 1e-9;
const double PI = acos(-1.0);
using namespace std;
int W, H;
int ans;
int dir[4][2] = {-1,0, 1,0, 0,-1, 0,1};
char ch[104][104];
struct p
{
int x, y;
}first, temp;
queue<p> qq;
char cc;
void bfs()
{
while(!qq.empty())
{
first = qq.front();
qq.pop();
for(int i = 0; i < 4; ++i)
{
temp.x = first.x + dir[i][0];
temp.y = first.y + dir[i][1];
if(ch[temp.x][temp.y] != -1 && ch[temp.x][temp.y] == cc)
{
qq.push(temp);
ch[temp.x][temp.y] = -1;
}
}
}
}
int main()
{
//freopen("test0.in", "r", stdin);
//freopen("test0.out", "w", stdout);
//srand(time(NULL));
while(~scanf("%d %d", &H, &W), H != 0 || W != 0)
{
ans = 0;
memset(ch, -1, sizeof(ch));
getchar();
for(int i = 1; i <= H; i++)
{
for(int j = 1; j <= W; j++)
{
ch[i][j] = getchar();
}
getchar();
}
for(int i = 1; i <= H; i++)
{
for(int j = 1; j <= W; j++)
{
if(ch[i][j] != -1)
{
cc = ch[i][j];
ch[i][j] = -1;
first.x = i, first.y = j;
qq.push(first);
bfs();
++ans;
}
}
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息