找出有多少个”水洼”(W的联通块)
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
解题思路
DFS
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 110;
char pic[maxn][maxn];
int vis[maxn][maxn];
int high,width;
int cnt = 0;
void dfs(int x,int y)
{
//第x行,第y列
if(pic[x][y] == ‘.‘ || vis[x][y]) return;
if(x<0 || y<0 || x>=high || y>=width) return;
vis[x][y] = 1;
dfs(x-1,y);dfs(x+1,y);dfs(x,y+1);dfs(x,y-1);
dfs(x-1,y-1);dfs(x-1,y+1);dfs(x+1,y-1);dfs(x+1,y+1);
}
int main()
{
scanf("%d%d",&high,&width);
for(int i = 0 ; i < high ; i ++) scanf("%s",pic[i]);
for(int i = 0 ; i < high ; i ++) {
for(int j = 0 ; j < width ; j ++) {
if(pic[i][j] == ‘.‘) continue;
if(vis[i][j] == 0) {
dfs(i,j);
cnt ++;
}
}
}
printf("%d\n",cnt);
return 0;
}
时间: 2024-11-02 19:02:13