UVA572oil deposits

来源:互联网 发布:淘宝导航条两边颜色 编辑:程序博客网 时间:2024/06/02 20:15

题目:

The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.

Input

The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either *, representing the absence of oil, or @, representing an oil pocket.

Output

For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.

Sample Input

1 1
*
3 5
@@*
@
@@*
1 8
@@**@*
5 5
**@
@@@
@*@
@@@*@
@@**@
0 0

Sample Output

0
1
2
2

题意

输入一个m行n列的字符矩阵,统计字符“@”组成多少个八连块。如果两个字符“@”所在的格子相邻(横、竖或者对角线方向),就说它们属于同一个八连块。

思路

对每个是油田的格子进行广度有限搜索:
1.找油田个数
如果要找到是单个油田块数
用一个简单的双层循环就行了
但是这次是找出它相连的油田的个数
所以对所有的的有油田的地方进行bfs
可以走的八个方向
当走过之后标记为一
二维数组储存这个地图
map[N][N];
vis;
搜索每个油田周围的状态
判断条件:
1.在边界之内
2.没走过
3.是油田

代码见下:

#include <iostream>#include<cstring>#include<queue>#include<algorithm>#include<cmath>using namespace std;#define N 100char map[N][N];bool vis[N][N];int a,b;int num;struct node{int x,y;};int dx[8]={1,-1,0,0,1,-1,-1,1};int dy[8]={0,0,1,-1,1,-1,1,-1};void bfs(){  memset(vis,0,sizeof(vis));  queue<node> q;  node u,v;  for(int i=0;i<a;i++)    for(int j=0;j<b;j++)  {    if(map[i][j]=='@'&&vis[i][j]==0){    ++num;    vis[i][j]=1;    u.x=i;    u.y=j;    q.push(u);    while(!q.empty())    {        u=q.front();        q.pop();        for(int k=0;k<8;k++){            v.x=u.x+dx[k];            v.y=u.y+dy[k];            if(vis[v.x][v.y]==0&&map[v.x][v.y]=='@'&&v.x>=0&&v.y>=0&&v.x<a&&v.y<b)            {              vis[v.x][v.y]=1;              q.push(v);            }        }    }  }}}int main(){    while(cin>>a>>b,(a+b))    {        for(int i=0;i<a;i++)        for(int j=0;j<b;j++)        cin>>map[i][j];        num=0;        bfs();        cout<<num<<endl;     }    return 0;}
原创粉丝点击