Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 24999 |
|
Accepted: 12619 |
Description
Input
Output
Sample Input
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
Sample Output
3
题意:图给出的是一片农场,'W'表示水, '.' 表示土地。问这片农场有多少块池塘。
dfs解法:从任意的W开始,不停地把邻接的部分用‘.’代替。1次dfs后与初始的W连接的所有W就都被替换成了‘.’ ,
直到图中不再存在W为止,总共进行的dfs次数就是答案。
代码如下:
#include<cstdio> int n,m; char map[110][110]; int dir[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; void dfs(int x,int y) { int i,nowx,nowy; map[x][y]='.';//将W替换成‘.’ for(i=0;i<8;++i)//遍历它的旁边8个方向 { nowx=x+dir[i][0]; nowy=y+dir[i][1]; if(nowx>=0&&nowx<n&&nowy>=0&&nowy<m&&map[nowx][nowy]=='W') dfs(nowx,nowy); } } int main() { int i,j,cnt; while(scanf("%d%d",&n,&m)!=EOF) { for(i=0;i<n;++i) scanf("%s",map[i]); cnt=0; for(i=0;i<n;++i) { for(j=0;j<m;++j) { if(map[i][j]=='W') { dfs(i,j); cnt++; } } } printf("%d\n",cnt); } return 0; }
bfs解法,解题思想与dfs一致,时间和内存也差不多
代码如下:
#include<cstdio> #include<queue> using namespace std; #define maxn 110 char map[maxn][maxn]; int n,m; int dir[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; struct node { int x,y; }a,temp; void bfs(int x,int y) { int i; queue<node>q; a.x=x; a.y=y; q.push(a); map[x][y]='.'; while(!q.empty()) { a=q.front(); q.pop(); for(i=0;i<8;++i) { temp.x=a.x+dir[i][0]; temp.y=a.y+dir[i][1]; if(temp.x>=0&&temp.x<n&&temp.y>=0&&temp.y<m&&map[temp.x][temp.y]=='W') { q.push(temp); map[temp.x][temp.y]='.'; } } } } int main() { int i,j,cnt; while(scanf("%d%d",&n,&m)!=EOF) { for(i=0;i<n;++i) scanf("%s",map[i]); cnt=0; for(i=0;i<n;++i) { for(j=0;j<m;++j) { if(map[i][j]=='W') { bfs(i,j); cnt++; } } } printf("%d\n",cnt); } return 0; }