POJ-2386 Lake Counting
原题链接:http://poj.org/problem?id=2386
专题链接:https://vjudge.net/contest/347799#problem/B
思路
创建一个二维字符数组,输入后遍历整个数组,找到一个“有水”的地方,就开始搜索,BFS和DFS均可,每搜到‘W’,就将‘W’转化为‘.’,每个搜索结束,就代表有一个水塘,直到遍历完整个数组即可输出答案。
AC代码
#include<cstdio>
#include<iostream>
using namespace std;
int N, M;
char arr[101][101];
int f[9][2] = { {0,0},{-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,1} ,{1,-1} ,{1,0}, {1,1} };//代表八个向量
int ans=0;
void dfs(int x, int y)
{
if (arr[x][y] != 'W')//没搜到W,就停止这条路的搜索
return;
arr[x][y] = '.';//搜到了就将W变为“,”,并且搜索其所在位置的八个方向
for (int k = 1; k <= 8; k++)
dfs(x + f[k][0], y+f[k][1]);
return;
}
int main()
{
cin >> N >> M;
for (int i = 1; i <= N; i++)//输入部分
scanf("%s", arr[i] + 1);
for (int i = 1; i <= N; i++)//遍历数组
{
for (int j = 1; j <= M; j++)
{
if (arr[i][j] == 'W')
{
dfs(i, j);
ans++;
}
}
}
cout << ans<<endl;
return 0;
}