pku 1562 Oil Deposits(典型的BFS)

来源:互联网 发布:菲诗小铺金盏花知乎 编辑:程序博客网 时间:2024/05/14 01:59

Description

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 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

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
这一题是最基本的广搜,只需要在搜到@后把与它相连的@全部变成*,每当搜到一个@,flag就+1,最后输出flag。
  1. #include<stdio.h>  
  2. #include<string.h>  
  3. #include<stdlib.h>  
  4. #include<iostream>  
  5. #include<queue>  
  6. using namespace std;  
  7. int m,n;  
  8. char a[105][105];  
  9. void find(int i,int j)  
  10. {  
  11.     int l,k,b,c;  
  12.     int dir[8][2]={{1,0},{-1,0},{0,1},{0,-1},{1,1},{-1,-1},{1,-1},{-1,1}};  
  13.     a[i][j]='*';  
  14.     for(l=0;l<8;l++)  
  15.     {  
  16.         b=i+dir[l][0];  
  17.         c=j+dir[l][1];  
  18.         if(b>=0&&c>=0&&b<m&&c<n&&a[b][c]=='@')  
  19.         {  
  20.             find(b,c);  
  21.         }  
  22.     }  
  23. }  
  24. int main()  
  25. {  
  26.     int i,j,k,l,flag=0;  
  27.     scanf("%d",&k);  
  28.     for(l=0;l<k;l++)  
  29.     {  
  30.         flag=0;  
  31.         scanf("%d%d",&m,&n);  
  32.         for(i=0;i<m;i++)  
  33.             scanf("%s",&a[i]);  
  34.         for(i=0;i<m;i++)  
  35.             for(j=0;j<n;j++)  
  36.             {  
  37.                 if(a[i][j]=='@')  
  38.                 {  
  39.                     flag++;  
  40.                     find(i,j);  
  41.                 }  
  42.             }  
  43.         printf("%d\n",flag);  
  44.     }  
  45.     return 0;  
  46. }  

原创粉丝点击