L - 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.
1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0
0 1 2 2
dfs模板题,问有多少块连在一起的油田
不解释直接上代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
using namespace std;
char a[120][150];
//bool b[120][150];
int sum,n,m;
void dfs(int x,int y)
{
if(x>=1&&x<=n&&y>=1&&y<=m)
{
//b[x][y]=1;
a[x][y]='*';//下次搜索时不能走这里
if(a[x-1][y]=='@') dfs(x-1,y);
if(a[x+1][y]=='@') dfs(x+1,y);
if(a[x][y+1]=='@') dfs(x,y+1);
if(a[x-1][y-1]=='@') dfs(x-1,y-1);
if(a[x+1][y-1]=='@') dfs(x+1,y-1);
if(a[x-1][y+1]=='@') dfs(x-1,y+1);
if(a[x+1][y+1]=='@') dfs(x+1,y+1);
if(a[x][y-1]=='@') dfs(x,y-1);
}
else return ;
}
int main()
{
while(cin>>n>>m&&m!=0&&n!=0)
{
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
{
cin>>a[i][j];
//b[i][j]=0;
}
sum=0;
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
if(a[i][j]=='@')//开始探索的条件
{
dfs(i,j);
sum++;
}
cout<<sum<<endl;
}
return 0;
}
直接把走过的地方设为不可走的*省去了判断的麻烦