L

来源:互联网 发布:系统优化软件2017 编辑:程序博客网 时间:2024/06/08 09:14

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
0122

还是一道简单的八方向的BFS


/*八个方向1=<行列 <=100 油田标记为@*/#include<iostream>#include<cstring>using namespace std;int M,N,total;char map[110][110];int visited[110][110];int dx[8]={-1, -1, 0, 1, 1, 1, 0, -1};//上-右上-右-右下-下-左下-左-左上 int dy[8]={ 0,  1, 1, 1, 0,-1,-1, -1};struct queue{int xx;int yy;}que[10100];void find_oil(int x,int y){int x1,y1;int head,tail;if(!visited[x][y]){total++;//第一次遍历  则加1    地图标记遍历过了 visited[x][y]=1;}if(visited[x][y]==1)//已经标记过,找周围的油田 {head=0,tail=1;que[0].xx=x;  //  注意刚才用的是  que[head].xx=x; que[0].yy=y;  //但是下面的循环会让head的值并非是0,所以 while(tail>head){x=que[head].xx; y=que[head].yy; for(int i=0;i<8;i++){x1=x+dx[i];y1=y+dy[i];//八个方向 if(x1>=1&&x1<=M&&y1>=1&&y1<=N)//判断是否越界 if(map[x1][y1]=='@'&&!visited[x1][y1]){que[tail].xx=x1;que[tail].yy=y1;visited[x1][y1]=1;tail+=1;}}head++;}}}void BFS(){for(int i=1;i<=M;i++)for(int j=1;j<=N;j++) if(map[i][j]=='@'&&!visited[i][j])find_oil(i,j);}int main(){ios::sync_with_stdio(false);while(cin>>M>>N){cin.get();if(M<=0||N<=0) break;total=0;memset(map,0,sizeof(map));memset(visited,0,sizeof(visited));//地图标记清0 for(int i=1;i<=M;i++)for(int j=1;j<=N;j++)cin>>map[i][j];/*for(int i=1;i<=M;i++){for(int j=1;j<=N;j++)cout<<map[i][j];cout<<endl;}*/BFS();cout<<total<<endl;}return 0; } 























































0 0