Lake Counting
| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 26822 | Accepted: 13466 |
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 就是循环检测发现是W 然后就深度搜索旁边的8个方块,这里用java ac了一发import java.util.Scanner; public class Main { static int maxn = 105 ; static char mapp[][] = new char[maxn][maxn]; static int n,m,ans; static int addx []= {-1,-1,-1,0,0,1,1,1} ; static int addy []= {-1,0,1,-1,1,-1,0,1} ; static void dfs(int x,int y){ mapp[x][y]='.' ; for(int i=0;i<8;i++){ int newx = x+addx[i] ; int newy = y+addy[i] ; if(newx>=0&&newx<=n&&newy>=0&&newy<=m&&mapp[newx][newy]=='W'){ //ans++ ; dfs(newx,newy); } } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in) ; while(in.hasNextInt()){ n = in.nextInt() ; m = in.nextInt() ; for(int i=0;i<n;i++){ String str = in.next() ; for(int j=0;j<m;j++){ mapp[i][j] = str.charAt(j) ; } } ans = 0 ; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(mapp[i][j]=='W'){ ans++ ; dfs(i,j); } } } System.out.println(ans); } } }
本文介绍了一个通过深度优先搜索算法解决湖泊计数问题的方法。该问题要求在一个由水('W')和陆地('.')组成的矩阵中计算湖泊的数量,湖泊定义为相连的水域集合。文章提供了一个Java实现示例,通过遍历矩阵并使用DFS标记和计数湖泊。
479

被折叠的 条评论
为什么被折叠?



