POJ 2386 Lake Counting
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.
Input
- Line 1: Two space-separated integers: N and M
- Lines 2..N+1: M characters per line representing one row of Farmer John's field. Each character is either 'W' or '.'. The characters do not have spaces between them.
Output
http://poj.org/problem?id=2386
- Line 1: The number of ponds in Farmer John's field.
#include <iostream> using namespace std; const int MAX_N = 100; char field[MAX_N][MAX_N+1]; int n, m; bool inRange(int x, int y){return x>=0 && x<n && y>=0 && y<m;} void dfs(int x, int y){ field[x][y] = '.'; //移動する8方向をループ for(int dx = -1 ; dx <= 1 ; dx++){ for(int dy = -1 ; dy <=1 ; dy++){ int nx = x+dx; int ny = y+dy; if(inRange(nx,ny) && 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(){ cin >> n >> m; for(int i=0 ; i<n ; i++){ for(int j=0 ; j<m ; j++){ cin >> field[i][j]; } } solve(); }
深さ優先探索(DFS: Depth-First Search)の例。