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.
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.
* 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
* Line 1: The number of ponds in Farmer John's field.
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
Java AC 代码:
1 import java.util.Scanner; 2 3 public class Main { 4 static int n,m,ans; 5 static char [][]filed = new char[105][105]; 6 public static void main(String[] args) { 7 Scanner cin = new Scanner(System.in); 8 while(cin.hasNext()) { 9 n = cin.nextInt(); 10 m = cin.nextInt(); 11 String s; 12 for(int i = 1;i <= n;i++) { 13 s = cin.next(); 14 for(int j = 1;j <= m;j++) { 15 filed[i][j] = s.charAt(j - 1); 16 } 17 } 18 Slove(); 19 System.out.println(ans); 20 } 21 } 22 23 private static void Slove() { 24 ans = 0; 25 for(int i = 1;i <= n;i++) { 26 for(int j = 1;j <= m;j++) { 27 if(filed[i][j] == 'W') { 28 DFS(i,j); 29 ans++; 30 } 31 } 32 } 33 } 34 35 private static void DFS(int x,int y) { 36 filed[x][y] = '.'; 37 for(int i = -1;i <= 1;i++) { 38 for(int j = -1;j <= 1;j++) { 39 int nx = x + i; 40 int ny = y + j; 41 if(filed[nx][ny] == 'W') { 42 DFS(nx,ny); 43 } 44 } 45 } 46 } 47 }