Skip to content

LeetCode: 841-Keys and Rooms 解題紀錄

Last Updated on 2022-12-20 by Clay

題目

There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.

Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.

Example 1:

Input: rooms = [[1],[2],[3],[]]
Output: true
Explanation: 
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.

Example 2:

Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.

Constraints:

  • n == rooms.length
  • 2 <= n <= 1000
  • 0 <= rooms[i].length <= 1000
  • 1 <= sum(rooms[i].length) <= 3000
  • 0 <= rooms[i][j] < n
  • All the values of rooms[i] are unique.

題目會給我們許多房間,每個房間內都有對應特定門的鑰匙。我們最一開始會擁有第 0 號房間的鑰匙,最後要判斷我們是否能走完所有的房間。


解題思路

今天工作較忙,只附上範例程式。

C++ 是 DFS、Python 是某種程度上的暴力解。


C++ 範例程式碼

class Solution {
public:
    void DFS(vector<vector<int>>& rooms, unordered_map<int, bool>& visited, int n) {
        for (auto& key: rooms[n]) {
            if (!visited[key]) {
                visited[key] = true;
                DFS(rooms, visited, key);
            }
        }
    }

    bool canVisitAllRooms(vector<vector<int>>& rooms) {
        unordered_map<int, bool> visited({{0, true}});
        DFS(rooms, visited, 0);

        return visited.size() == rooms.size();
    }
};



Python 範例程式碼

class Solution:
    def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
        setA = set([0])
        setB = set()
        setC = set([0])

        while setC:
            for n in setC:
                setB.update(set(rooms[n]))

            setC = setB.difference(setA)
            setA.update(setB)
            setB.clear()

        return len(setA) == len(rooms)

References


Read More

Leave a Reply