其他分享
首页 > 其他分享> > P2815 城堡问题

P2815 城堡问题

作者:互联网

题目链接:城堡问题

有一个小技巧:

input作为砖块数字的输入

1&input,2&input,4&input,8&input

分别表示左上右下的砖块.如果结果是0,说明这个位置没有砖块.

剩下就是深度优先搜索.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
    static boolean[][] isSearched;
    static int[][][] wDatas;
    static int maxAreaCnt=0;
    static int tempAreaCnt=0;
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int height = Integer.parseInt(st.nextToken());
        st = new StringTokenizer(br.readLine());
        int width = Integer.parseInt(st.nextToken());
        //0:left 1:top 2:right 3:down
        wDatas = new int[height+1][width+1][4];
        int input;
        for(int i = 1;i<=height;i++){
            st = new StringTokenizer(br.readLine());
            for(int j = 1;j<=width;j++){
                input = Integer.parseInt(st.nextToken());
                wDatas[i][j] = new int[]{1&input,2&input,4&input,8&input};
            }
        }
        isSearched = new boolean[height+1][width+1];
        int cnt=0;
        for(int i =1;i<=height;i++){
            for(int j = 1;j<=width;j++){
                if(!isSearched[i][j]){
                    dfs(i,j);
                    cnt++;
                    //System.out.println(tempAreaCnt);
                    //System.out.println("===");
                    maxAreaCnt = Math.max(maxAreaCnt,tempAreaCnt);
                    tempAreaCnt = 0;
                }
            }
        }
        System.out.println(cnt);
        System.out.println(maxAreaCnt);
    }
    private static void dfs(int h,int w){
        isSearched[h][w] = true;
        //System.out.println(h+"  "+w);
        tempAreaCnt++;
        int[] currentWall = wDatas[h][w];
        if(currentWall[0] == 0&&w-1>0 &&!isSearched[h][w-1]){
            dfs(h,w-1);
        }
        if(currentWall[1]==0&&h-1>0&&!isSearched[h-1][w]){
            dfs(h-1,w);
        }
        if(currentWall[2]==0&&w+1<wDatas[0].length&&!isSearched[h][w+1]){
            dfs(h,w+1);
        }
        if(currentWall[3]==0&&h+1<wDatas.length&&!isSearched[h+1][w]){
            dfs(h+1,w);
        }
    }
}


标签:int,城堡,问题,P2815,static,StringTokenizer,&&,new,input
来源: https://www.cnblogs.com/reclusiveone/p/14722571.html