城堡问题

这里写图片描述
这里写图片描述
这里写图片描述

public class Main{

    static int r,c;//行列数
    static int[][]rooms = new int[60][60];
    static int[][]color = new int[60][60];       //房间是否染过颜色
    static int maxRoomArea=0;  //最大房间面积
    static int roomNum=0;      //房间的数量
    static int roomArea;       //正在探索的房间的面积
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        r = in.nextInt();
        c = in.nextInt();
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                rooms[i][j] = in.nextInt();

        for(int i=0;i<r;i++) {
            for(int j=0;j<c;j++) {
                   //如果未被染色,说明该房间可走
                if(color[i][j]==0) {
                    roomNum++;roomArea=0;
                    Dfs(i,j);
                    maxRoomArea = Math.max(maxRoomArea, roomArea);
                }
            }
        }
        System.out.println(roomNum+"\n"+maxRoomArea);
        in.close();
    }
    private static void Dfs(int i, int j) {

        if(color[i][j]!=0)return;

        ++roomArea;
        color[i][j] = roomNum;
        //1西墙,2北墙,4东墙,8南墙
        //0001 0010 0100 1000
        //将rooms[i][j]与墙对应的数字相与,如果为0说明不存在该墙,则可以向该方向移动
        if((rooms[i][j] & 1)==0)Dfs(i, j-1);   //向西走
        if((rooms[i][j] & 2)==0)Dfs(i-1, j);   //向北走
        if((rooms[i][j] & 4)==0)Dfs(i, j+1);   //向东走
        if((rooms[i][j] & 8)==0)Dfs(i+1, j);   //向南走
    }

}

猜你喜欢

转载自blog.csdn.net/l903445981/article/details/80151665