鏈接:https://www.luogu.com.cn/problem/P1596
題目描述
由于近期的降雨,雨水匯集在農(nóng)民約翰的田地不同的地方。我們用一個NxM(1<=N<=100;1<=M<=100)網(wǎng)格圖表示。每個網(wǎng)格中有水('W') 或是旱地('.')。一個網(wǎng)格與其周圍的八個網(wǎng)格相連,而一組相連的網(wǎng)格視為一個水坑。約翰想弄清楚他的田地已經(jīng)形成了多少水坑。給出約翰田地的示意圖,確定當中有多少水坑。
輸入格式
第1行:兩個空格隔開的整數(shù):N 和 M
第2行到第N+1行:每行M個字符,每個字符是'W'或'.',它們表示網(wǎng)格圖中的一排。字符之間沒有空格。
輸出格式
- 一行:水坑的數(shù)量
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
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
理解:
??'W'代表著積水,而'.'代表著干的地。而如果兩個積水距距離<2則視作同一片水洼,求圖中水洼的總量。顯而易見,需要遍歷所有積水,并確定它的周圍八個點是否都為干地,利用深度優(yōu)先算法。
題解:
#include <iostream>
using namespace std;
#define MAX 100
int n, m;
char arr[MAX][MAX];
void dfs(int x, int y)
{
arr[x][y] = '.';
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++)
{
int nx = x + dx;
int ny = y + dy;
if (nx >= 0 && ny >= 0 && nx < n && ny < m && arr[nx][ny] == 'W')
dfs(nx, ny);
}
return;
}
int main()
{
int num = 0;
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> arr[i][j];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
if (arr[i][j] == 'W')
{
dfs(i, j);
num++;
}
}
cout << num << endl;
system("pause");
}