天天看點

POJ 2386 Lake Counting(簡單的深度搜尋)

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.

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

* 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);
			
		}
	}

}