内存:128  时间:1

题目描述

Farmer John purchased satellite photos of W x H pixels of his farm (1 <= W <= 80, 1 <= H <= 1000) and wishes to determine the largest ‘contiguous’ (connected) pasture. Pastures are contiguous when any pair of pixels in a pasture can be connected by traversing adjacent vertical or horizontal pixels that are part of the pasture. (It is easy to create pastures with very strange shapes, even circles that surround other circles.)

Each photo has been digitally enhanced to show pasture area as an asterisk (‘*’) and non-pasture area as a period (‘.’). Here is a 10 x 5 sample satellite photo:

..*.....**
.**..*****
.*...*....
..****.***
..****.***

This photo shows three contiguous pastures of 4, 16, and 6 pixels. Help FJ find the largest contiguous pasture in each of his satellite photos.

输入

* Line 1: Two space-separated integers: W and H
* Lines 2..H+1: Each line contains W "*" or "." characters representing one raster line of a satellite photograph.

 

输出

* Line 1: The size of the largest contiguous field in the satellite photo.

样例输入

10 5
..*…..**
.**..*****
.*…*….
..****.***
..****.***

样例输出

16

提示

代码如下

import java.util.Scanner;

public class Main {
	static char[][] data;
	static boolean[][] used;
	static int W;
	static int H;
	public static void main(String[] args){    
    	Scanner scanner = new Scanner(System.in);
    	W = scanner.nextInt();
    	H = scanner.nextInt();
    	data = new char[H][W];
    	used = new boolean[H][W];
    	for(int i=0;i<H;i++){
    		String s = scanner.next();
    		for(int j=0;j<W;j++){
    			data[i][j] = s.charAt(j);
    		}
    	}
    	int max = Integer.MIN_VALUE;
    	for(int i=0;i<H;i++){
    		for(int j=0;j<W;j++){
    			if(used[i][j]==false&&data[i][j]=='*'){
    				int n = dfs(j,i);
    				if(max<n){
    					max = n;
    				}
    			}
    		}
    	}
    	System.out.println(max);
	}
	public static int dfs(int x,int y){
		if(x<0||x>=W||y<0||y>=H){
			return 0;
		}
		if(data[y][x]=='.'){
			return 0;
		}
		if(used[y][x]==true){
			
			return 0;
		}else{
			used[y][x] = true;
			return 1+dfs(x-1,y)+dfs(x+1,y)+dfs(x,y+1)+dfs(x,y-1);
		}
		
	}

}

代码来源于互联网,仅供参考!