dfs-求连通块

状态:若为W则继续搜索

import java.util.Scanner;

public class Main {
    static int n,m;
    static char[][] field;
    
    static void dfs(int row, int col){
        field[row][col] = '@';
        for(int dx = -1; dx <= 1; dx++){
            for(int dy = -1; dy <= 1; dy++){
                int newRow = row + dx;
                int newCol = col + dy;
                if(newRow >= 0 && newRow < n && newCol >=0 && newCol < m && field[newRow][newCol]=='W'){                
                    dfs(newRow,newCol);
                }
            }            
        }    
    
    }
    

    public static void main(String[] args) {
        
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        m = in.nextInt();
        field = new char[n][m];
        
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++)
              field[i][j] = in.next().charAt(0);
        }
            
                
        
        int ans = 0;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                
                if(field[i][j]=='W'){
                    dfs(i,j);
                    ans++;
                }

            }
        }
        
        System.out.println(ans);


    }

}

 

posted @ 2017-03-31 12:44  Gladitor  阅读(216)  评论(0编辑  收藏  举报