题解 | 数水坑

数水坑

https://www.nowcoder.com/practice/664ca4289fcf457ba3109fdf4a7a1a05

dfs

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void dfs(char[][] chs,int i,int j){
        if(chs[i][j]=='.'){
            return ;
        }
        chs[i][j]='.';
        if(i-1>=0){
            dfs(chs,i-1,j);
        }
        if(i+1<N){
            dfs(chs,i+1,j);
        }
        if(j-1>=0){
            dfs(chs,i,j-1);
        }
        if(j+1<M){
            dfs(chs,i,j+1);
        }
        if(i-1>=0&&j-1>=0){
            dfs(chs,i-1,j-1);
        }
        if(i-1>=0&&j+1<M){
            dfs(chs,i-1,j+1);
        }
        if(i+1<N&&j+1<M){
            dfs(chs,i+1,j+1);
        }
        if(i+1<N&&j-1>=0){
            dfs(chs,i+1,j-1);
        }
    }
    static int N;
    static int M;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        N=in.nextInt();
        M=in.nextInt();
        char[][] chs=new char[N][M];
        for(int i=0;i<N;i++){
            chs[i]=in.next().toCharArray();
        }
        long count=0;
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                if(chs[i][j]=='W'){
                    count++;
                    dfs(chs,i,j);
                }

            }
        }
        System.out.println(count);

    }
}

全部评论

相关推荐

LZStarV:冲就好了,就算真的是字节也冲,面评脏了大不了等三四个月就淡了,而且等到那个时候实力进步了选择还多,何必拘泥于字节
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务