leetcode 841.钥匙和空间 Java

做题博客链接

https://blog.csdn.net/qq_43349112/article/details/108542248

题目链接

https://leetcode-cn.com/problems/keys-and-rooms/

描述

有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:012...,N-1,并且房间里可能有一些钥匙能
使你进入下一个房间。

在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j][0,1...,N-1] 中的一个
整数表示,其中 N = rooms.length。 钥匙 rooms[i][j] = v 可以打开编号为 v 的房间。

最初,除 0 号房间外的其余所有房间都被锁住。

你可以自由地在房间之间来回走动。

如果能进入每个房间返回 true,否则返回 false。


提示:

1 <= rooms.length <= 1000
0 <= rooms[i].length <= 1000
所有房间中的钥匙数量总计不超过 3000

示例

示例 1:

输入: [[1],[2],[3],[]]
输出: true
解释:  
我们从 0 号房间开始,拿到钥匙 1。
之后我们去 1 号房间,拿到钥匙 2。
然后我们去 2 号房间,拿到钥匙 3。
最后我们去了 3 号房间。
由于我们能够进入每个房间,我们返回 true

示例 2:

输入:[[1,3],[3,0,1],[2],[0]]
输出:false
解释:我们不能进入 2 号房间。

初始代码模板

class Solution {
    
    
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
    
    
        
    }
}

代码

模板题

推荐题解:
https://leetcode-cn.com/problems/keys-and-rooms/solution/yao-chi-he-fang-jian-by-leetcode-solution/

class Solution {
    
    
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
    
    
        int n = rooms.size();
        boolean[] vis = new boolean[n];
        int surplus = n - 1;
        vis[0] = true;
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);
        while (!queue.isEmpty() && surplus > 0) {
    
    
            for (int size = queue.size(); size > 0; size--) {
    
    
                int key = queue.poll();
                for (int val : rooms.get(key)) {
    
    
                    if (!vis[val]) {
    
    
                        queue.offer(val);
                        vis[val] = true;
                        surplus--;
                    }
                }
            }
        }

        return surplus == 0;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43349112/article/details/115219739
今日推荐