POJ 1562(L - 暴力求解、DFS)
油田问题(L - 暴力求解、DFS)
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
0 1 2 2
题目大意:
@代表有油田,*代表没有油田。相邻的两个@代表一个油田,输入一个二维数组找出这个数组里共有多少油田?
分析:
1.这是一个典型的八皇后问题,需要从8个方向遍历搜索
2.DFS(深度优先搜索)、递归方法
3.找到一个@后,从8个方向遍历,并记录sum++
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <iostream> 3 using namespace std; 4 5 char map[101][101]; 6 int n,m,sum; 7 8 void dfs(int i,int j) 9 { 10 if(map[i][j]!='@'||i<0||j<0||i>=m||j>=n) //不是油田或是边界 11 return; 12 else //从8个方向搜索 13 { 14 map[i][j]='!'; 15 dfs(i-1,j-1); 16 dfs(i-1,j); 17 dfs(i-1,j+1); 18 dfs(i,j-1); 19 dfs(i,j+1); 20 dfs(i+1,j-1); 21 dfs(i+1,j); 22 dfs(i+1,j+1); 23 } 24 } 25 26 int main() 27 { 28 int i,j; 29 while(scanf("%d%d",&m,&n)!=EOF) 30 { 31 if(m==0||n==0) 32 break; 33 sum=0; 34 for(i=0;i<m;i++) 35 for(j=0;j<n;j++) 36 cin>>map[i][j]; 37 for(i=0;i<m;i++) 38 { 39 for(j=0;j<n;j++) 40 { 41 if(map[i][j]=='@') //以map[i][j]=='@'为中心 42 { 43 dfs(i,j); 44 sum++; 45 } 46 } 47 } 48 printf("%d\n",sum); 49 } 50 51 return 0; 52 }
这道题很明显和8皇后问题类似,所以解起来还很简单。