Oil Deposits(DFS模板题)

来源:互联网 发布:linux 获取函数返回值 编辑:程序博客网 时间:2024/06/05 17:18

点击打开链接

                                  Oil Deposits

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
题解:这是DFS(深度优先搜索)的模板题,第一次学懂,数组的范围要适中第一次数组,所以wa了一次,说是内存过大,把模板保留一下;

下面是我的代码:

#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<queue>#include<cstdlib>#define MAX 110using namespace std;char map[MAX][MAX];//用来放地图用的 int vis[MAX][MAX];//数组不宜开太大,不然会超出内存int n,m,ans;int fx[8]={0,0,-1,1,-1,1,-1,1},fy[8]={-1,1,0,0,-1,1,1,-1};//上,下,左,右,左上,右下,左下,右上; void dfs(int x,int y){vis[x][y]=1;for(int i=0;i<8;i++){int xx=x+fx[i],yy=y+fy[i];    if(xx>=0&&yy>=0&&xx<n&&yy<m&&!vis[xx][yy]&&map[xx][yy]=='@')    //用来检测是否超出了地图的边界,如果满足条件的话继续搜索      dfs(xx,yy);//递归调用 }   }int main(){while(scanf("%d%d",&n,&m)&&(n||m)){ans=0;memset(vis,0,sizeof(vis));//每搜索一次要清空一次for(int i=0;i<n;i++)scanf("%s",map[i]);for(int i=0;i<n;i++)for(int j=0;j<m;j++){if(!vis[i][j]&&map[i][j]=='@'){ans++;//统计最后的个数 dfs(i,j);}}printf("%d\n",ans); } } 

这里附上关于深度搜索的博客

点击打开链接






原创粉丝点击