poj2386
Description
Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water ('W') or dry land ('.'). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.
Given a diagram of Farmer John's field, determine how many ponds he has.
Thinking
Typical DFS
Answer
#include <iostream>
#define MAX_N 100
#define MAX_M 100
using namespace std;
int n, m;
char field[MAX_N][MAX_M];
void input(){
cin >> n >> m;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
char ch;
cin >> ch;
while (ch != '.' && ch != 'W'){
cin >> ch;
}
field[i][j] = ch;
}
}
}
void dfs(int x, int y){
// 将当前所在位置替换为.
field[x][y] = '.';
// 遍历八方向
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
int nx = x + dx, ny = y + dy;
if (0 <= nx && nx < n && 0 <= ny && ny < m && field[nx][ny] == 'W')
dfs(nx, ny);
}
}
}
void solve(){
int res = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (field[i][j] == 'W'){
dfs(i, j);
res++;
}
}
}
cout << res << endl;
}
int main(){
input();
solve();
}