首页 > 代码库 > POJNo.2386

POJNo.2386

(http://poj.org/problem?id=2386)

public class Main {
    int N;
    int M;
    char[][] garden;
    
    public Main(int N, int M, char[][] garden){
        this.N = N;
        this.M = M;
        this.garden = garden;
    }
    
    void dfs(int x, int y){
        garden[x][y] = ‘.‘;
        
        //printGarden();
        //System.out.println("=======================");
        
        for(int dx = -1; dx <= 1; dx++){
            for(int dy = -1; dy <= 1; dy++){
                int nx = x + dx;
                int ny = y + dy;
                if(nx>=0 && nx< N && ny>= 0 && ny < M){
                    if(garden[nx][ny] == ‘W‘){
                        dfs(nx, ny);
                    }
                }
            }
        }
    }

    int resolve(){
        int res = 0;
        for(int i = 0; i< N; i++){
            for(int j = 0; j< M; j++){
                if(garden[i][j] == ‘W‘){
                    dfs(i,j);
                    res++;
                }
            }
        }
        return res;
    }
    
    //打印整个过程
    void printGarden(){
        for(int i = 0; i< garden.length; i++){
            char[] row = garden[i];
            for(int j = 0; j<row.length; j++){
                System.out.print(row[j]+" ");
            }
            System.out.println();
        }
    }
    
    public static void main(String[] args){

        char[][] garden = {
                {‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘},
                {‘.‘,‘W‘,‘W‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘W‘},
                {‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘},
                {‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘},
                {‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘,‘.‘},
                {‘.‘,‘.‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘,‘.‘},
                {‘.‘,‘W‘,‘.‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘W‘,‘.‘},
                {‘W‘,‘.‘,‘W‘,‘.‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘},
                {‘.‘,‘W‘,‘.‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘},
                {‘.‘,‘.‘,‘W‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘W‘,‘.‘},
        };
        int N = garden.length;
        int M = garden[0].length;
        System.out.println(N+", "+M);
        
        Main test = new Main(N,M,garden);
        int res = test.resolve();
        System.out.println(res);
    }
    
}

 

POJNo.2386