#include<bits/stdc++.h>
using namespace std;
int n, m, ans;
int dx[] = {1, -1, 0, 0};//方向数组
int dy[] = {0, 0, 1, -1};
char a[101][101];
void dfs(int x, int y)
{
a[x][y] = '.';//已经走过
int nx, ny;
for(int i = 0; i < 4; i ++)
for(int j = 0; j < 4; j ++)
{
nx = x + dx[i];//四处查找
ny = y + dy[i];
if(nx >= 0 && x <= n && ny >= 0 && y <= m && a[nx][ny] == 'W')//判断边界
dfs(nx, ny);//回溯搜索
}
}
int main()
{
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
cin >> a[i][j];
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
if(a[i][j] == 'W')//查找到就搜
{
dfs(i, j);
ans ++;//答案加一
}
cout << ans << "\n";
return 0;
}
很好奇下面根据第一篇题解写的代码为啥答案就对了:
#include<bits/stdc++.h>
using namespace std;
int n, m, ans;
int dx[] = {1, -1, 0, 0};//方向数组
int dy[] = {0, 0, 1, -1};
char a[101][101];
void dfs(int x, int y)
{
a[x][y] = '.';//已经走过
int nx, ny;
for(int i = -1; i <= 1; i ++)//就从这里开始是看着题解写的
for(int j = -1; j <= 1; j ++)
{
nx = x + i;//四处查找(这里也是)
ny = y + j;
if(nx >= 0 && x <= n && ny >= 0 && y <= m && a[nx][ny] == 'W')//判断边界(后面的和原来一样)
dfs(nx, ny);//回溯搜索
}
}
int main()
{
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
cin >> a[i][j];
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
if(a[i][j] == 'W')//查找到就搜
{
dfs(i, j);
ans ++;//答案加一
}
cout << ans << "\n";
return 0;
}