【DFS】Oil Deposits

来源:互联网 发布:命令与征服5知乎 编辑:程序博客网 时间:2024/06/05 00:57

//后面有我个人的想法和题目的分析

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. 

--------------

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. 

--------------

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. 

---------------

1 1*3 5*@*@***@***@*@*1 8@@****@*5 5 ****@*@@*@*@**@@@@*@@@**@0 0 
-----------

0122
-----------

大意:就是找连在一起的@,斜对角和上下左右。

讲道理,这题不是hin DFS,反而有些BFS遍历的感觉,一般都有用一个book[][]来记录是否走过那个格子,但是这个题为什么不考虑直接讲'@'变成'#'呢?

感谢一位给我讲了思路的学长!






#include <stdio.h>#include <string.h>char maps[105][105];int  dir[8][2]={{1,1},{1,-1},{1,0},{0,1},{0,-1},{-1,0},{-1,1},{-1,-1}};int  m,n;int  tx,ty;int  sum=0;void dfs(int x,int y){int i;for(i=0;i<8;i++){tx=x+dir[i][0];ty=y+dir[i][1];if(maps[tx][ty]!='@'|| x<0 || x>m-1 || y<0 || y>n-1)//判断是否越界continue;maps[tx][ty]='#';//更改dfs(tx,ty);}}int main(){int i;int j;while(~scanf("%d %d",&m,&n)){sum=0;if(m==0 && n==0)break;for(i=0;i<m;i++){scanf("%s",maps[i]);}for(i=0;i<m;i++){for(j=0;j<n;j++){if(maps[i][j]=='@'){//maps[tx][ty]='#';dfs(i,j);sum++;}}}printf("%d\n",sum);}return 0;}


0 0
原创粉丝点击