Oil Deposits 深度优先搜素油田

来源:互联网 发布:360水滴破解软件 编辑:程序博客网 时间:2024/05/16 08:39
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. <br>

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

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

Sample Input
1 1<br>*<br>3 5<br>*@*@*<br>**@**<br>*@*@*<br>1 8<br>@@****@*<br>5 5 <br>****@<br>*@@*@<br>*@**@<br>@@@*@<br>@@**@<br>0 0 <br>

Sample Output
0<br>1<br>2<br>2<br>
这是第一道深度搜索的题对我来说,正好入门。
题意:@代表油田,输入m,n即为矩阵,查看@有几组可以连成一块的,条件是8个方向的临接。
#include<iostream>#include<cmath>#include<cstring>#include<stdio.h>using namespace std;char map[201][201];int mark[201][201];int m,n;int direction[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};//方向,面向八个方向void dfs(int i,int j){    int x1,y1;    mark[i][j] = 1;//已经搜索过为1    for(int d=0;d<8;++d)    {        x1 = i+direction[d][0];        y1 = j+direction[d][1];        if(map[x1][y1]!='@'||mark[x1][y1])            continue;            dfs(x1,y1);//递归来进行搜索某一组    }}int main(){    int sum = 0;    while(cin>>m>>n)    {        if(m==0||n==0)        {            break;        }        sum = 0;    for(int i=0;i<m;++i)    {        for(int j=0;j<n;++j)        {            cin>>map[i][j];            mark[i][j] = 0;//没被访问记为0        }    }      for(int i=0;i<m;++i)    {        for(int j=0;j<n;++j)        {           if(map[i][j]=='@'&&!mark[i][j])           {               dfs(i,j);               ++sum;           }        }    }    cout<<sum<<endl;    memset(mark,0,sizeof(mark));//每次对数组进行初始化    memset(map,'0',sizeof(map));    }    return 0;}
0 0
原创粉丝点击