首页 > 专题系列 > Java解POJ > POJ 2386 Lake Counting [解题报告] Java
2013
11-11

POJ 2386 Lake Counting [解题报告] Java

Lake Counting

问题描述 :

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.

输入:

* 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.

输出:

* Line 1: The number of ponds in Farmer John’s field.

样例输入:

10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.

样例输出:

3

温馨提示:

OUTPUT DETAILS:

There are three ponds: one in the upper left, one in the lower left,and one along the right side.

解题代码:

//* @author: [email protected]
import java.util.Scanner;
public class Main
{
 public static void main(String[] args)
 {
  Scanner in=new Scanner(System.in);
  int a=in.nextInt();
  int b=in.nextInt();
  int count=0;
  int[][] arr=new int[a+2][b+2];
  for(int i=1;i<=a;i++){
   String s=in.next();
   for(int j=1;j<=b;j++)
    arr[i][j]=s.charAt(j-1);
  }
  for(int i=1;i<=a;i++)
   for(int j=1;j<=b;j++)
     if(arr[i][j]==87){
	find(arr,i,j);
	count++;
      }
   System.out.println(count);
				
   }

  public static void find(int[][] a,int i,int j)
  {
   if(a[i][j]==87)
   {
	a[i][j]=65;
	for(int k=i-1;k<=i+1;k++)
          for(int w=j-1;w<=j+1;w++)
	    if(a[k][w]==87)find(a,k,w);
   }
 }
}

  1. 第二种想法,我想来好久,为啥需要一个newhead,发现是把最后一个节点一直返回到嘴上面这层函数。厉害,这道题之前没样子想过。