洛谷 P1506 拯救oibh总部 Java

import java.io.*;
import java.util.*;

public class Main{

    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    static String[][] map;
    static int x,y,cnt;
    static int[] X = new int[]{-1,1,0,0};
    static int[] Y = new int[]{0,0,-1,1};

    public static void main(String[] args) throws IOException {
        String[] STR = br.readLine().split(" ");
        x = Integer.parseInt(STR[0]);
        y = Integer.parseInt(STR[1]);
        map = new String[x+2][y+2];
        for(int i = 1 ; i <= x ; i++){
            STR = br.readLine().split("");
            for(int j = 1 ; j <= y ; j++){
                map[i][j] = STR[j-1];
            }
        }
        DFS(0,0);
        for(int i = 1 ; i <= x ; i++){
            for(int j = 1 ; j <= y ; j++){
                if(Objects.equals(map[i][j], "0")){
                    cnt++;
                }
            }
        }
        out.write(cnt + "");
        out.flush();
        out.close();
        br.close();
    }

    public static void DFS(int a , int b){
        if(a < 0 || b < 0 || a > x + 1 || b > y + 1 || Objects.equals(map[a][b], "*")){
            return ;
        }
        map[a][b] = "*";
        for(int i = 0 ; i < 4 ; i++){
            DFS(a + X[i] , b + Y[i]);
        }
    }
}

你可能感兴趣的:(洛谷刷题之旅,java,算法,深度优先)