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
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
思路:
我在做这道题目的时候遇到的最大的困难是题意了,我读了很久的描述也没有弄明白什么是水洼,看了下面的提示
,无法从样例中找到所说的三个水洼。后来终于搞明白水洼必须是连续的‘W',也就是说一个水洼其实就是一片连起来的’
W',弄清了题意就可以使用dfs进行求解了,从任意一个'w'开始调用dfs()会把一片连续的'w'替换掉,多次调用,直到没有
'W'为止.这样调用dfs()的次数就是答案
易错:
其中的'W'是大写,要看清楚
import java.util.Scanner; import java.util.Stack; public class Main { static Scanner scanner = new Scanner(System.in); static int n; static int m; static char [][] a; public static void main(String[] args) { n = scanner.nextInt(); m = scanner.nextInt(); a = new char[n][m]; for(int i = 0;i<n;i++){ String string = scanner.next(); a[i] = string.toCharArray(); } int ans = 0; for(int i = 0;i<n;i++){ for(int j = 0;j<m;j++){ if(a[i][j]=='W'){ dfs(i,j); ans++; } } } System.out.println(ans); } static void dfs(int x,int y){ if(a[x][y] == 'W'){ a[x][y] = '.'; } for(int dx = -1;dx<=1;dx++){ for(int dy = -1;dy<=1;dy++){ int i = x + dx; int j = y + dy; if(i>=0&&i<n&&j>=0&&j<m&&a[i][j]=='W'){ dfs(i,j); } } } } }