题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=27
本题是一道全覆盖的搜索题,建议遇到全覆盖问题先采用dfs,dfs不行再选用bfs,而且本题采用了DFS,这道题和POJ上的一道题进行比较,两题只差在相邻的几个点算一个池子
水池数目:必须在DFS中更新地图标记
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=110;
int mp[maxn][maxn];
int m,n;
const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};
int step;
void dfs(int x,int y)
{
int xx,yy;
mp[x][y]=0;
for(int i=0;i<4; i++)
{
xx=x+dx[i];
yy=y+dy[i];
if(xx>=0&&yy>=0&&xx<m&&yy<n&&mp[xx][yy])
dfs(xx,yy);
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>m>>n;
step=0;
memset(mp,'1',sizeof(mp));
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>mp[i][j];
}
}
for(int i=0; i<m; i++)
{
for(int j=0; j<n;j++)
{
if(mp[i][j]==1)
{
dfs(i,j);
step++;
// mp[i][j]=0;
}
}
}
cout<<step<<endl;
}
return 0;
}
Lake Counting:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int dx[8]={1,0,-1,0,1,-1,1,-1};
const int dy[8]={0,1,0,-1,-1,-1,1,1};
const int maxn=110;
//bool vis[maxn][maxn];
char mp[maxn][maxn];
int n,m;
int step;
void dfs(int x,int y)
{
int xx,yy;
//vis[x][y]=true;
mp[x][y]='.';
for(int i=0; i<8; i++)
{
xx=x+dx[i];
yy=y+dy[i];
if(xx>=0&&yy>=0&&xx<n&&yy<m&&/*!vis[xx][yy]&&*/mp[xx][yy]=='W')
{
dfs(xx,yy);
//vis[xx][yy]=false;
}
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
step=0;
//memset(vis,false,sizeof(vis));
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin>>mp[i][j];
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(mp[i][j]=='W')
{
dfs(i,j);
step++;
}
}
}
cout<<step<<endl;
}
}