Oil Deposits
Sample Input
1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5
****@
*@@*@
*@**@
@@@*@
@@**@
0 0
Sample Output
0
1
2
2
题意:问地图中有多少个@,前提如果@的八个方向中如果还是@,则相邻的@不进入计数。(简单的BFS)
代码:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<string>
#include<queue>
using namespace std;
struct node
{
int x;
int y;
} q[10010];
int jx[] = {0,1,0,-1,1,1,-1,-1};
int jy[] = {1,0,-1,0,1,-1,1,-1};
int n,m;
char map[101][101];
int v[101][101];
int pt;
void BFS()
{
node t,f;
memset(v,0,sizeof(v));
queue<node>p;
int count = 0;
for(int i=0; i<pt; i++)
{
if(v[q[i].x][q[i].y] == 0)
{
t.x = q[i].x;
t.y = q[i].y;
v[t.x][t.y] = 1;
count++;
p.push(t);
while(!p.empty())
{
t = p.front();
p.pop();
for(int j=0;j<8;j++)
{
f.x = t.x + jx[j];
f.y = t.y + jy[j];
if(f.x>=0 && f.x<n && f.y>=0 && f.y<m && map[f.x][f.y] == '@' && v[f.x][f.y] == 0)
{
p.push(f);
v[f.x][f.y] = 1;
}
}
}
}
}
printf("%d\n",count);
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n == 0 && m == 0)
{
break;
}
pt = 0;
struct node a;
for(int i=0; i<n; i++)
{
scanf("%s",map[i]);
for(int j=0; j<m; j++)
{
if(map[i][j] == '@')
{
a.x = i;
a.y = j;
q[pt++] = a;
}
}
}
BFS();
}
return 0;
}
Miguel A. Revilla
1998-03-10