hdu 1241:Oil Deposits(DFS)

8624 ワード

Oil Deposits
Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 4   Accepted Submission(s) : 3
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem 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
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


Source
Mid-Central USA 1997
 
これは経典dfs検索問題で、難易度は入門級に属し、あまり難しいところはありません.
コードは次のとおりです.
 
 1 #include <iostream>

 2 using namespace std;  3 char a[101][101];  4 int dx[8] = {0,1,1,1,0,-1,-1,-1};  5 int dy[8] = {1,1,0,-1,-1,-1,0,1};  6 int m,n;  7 void dfs(int x,int y)    // (x,y)               * 

 8 {  9     a[x][y]='*'; 10     for(int i=0;i<8;i++){ 11         int nx = x+dx[i]; 12         int ny = y+dy[i]; 13         if( nx<1 || ny<1 || nx>m || ny>n)    //     

14             continue; 15         if(a[nx][ny]!='@')    //            @ 

16             continue; 17  dfs( nx , ny ); 18  } 19 } 20 int main() 21 { 22     while(cin>>m>>n,m!=0){ 23         int _count=0; 24         for(int i=1;i<=m;i++) 25             for(int j=1;j<=n;j++) 26                 cin>>a[i][j]; 27         for(int i=1;i<=m;i++) 28             for(int j=1;j<=n;j++){ 29                 if(a[i][j]=='@'){ 30                     _count++; 31  dfs(i,j); 32  } 33  } 34         cout<<_count<<endl; 35  } 36     return 0; 37 }

  
Freecode : www.cnblogs.com/yym2013