Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 841. Keys and Rooms

Rain Hu

841. Keys and Rooms


一、題目

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:

Example 2:

Constraints:


二、分析

三、解題

1. BFS

bool canVisitAllRooms(vector<vector<int>>& rooms) {
    queue<int> q;
    q.push(0);
    int cnt = rooms.size();
    vector<bool> used(rooms.size(), false);
    while (!q.empty()){
        int key = q.front();
        q.pop();
        if (used[key]) continue;
        cnt--;
        if (cnt == 0) break;
        used[key] = true;
        for (int next : rooms[key]){
            if (used[next]) continue;
            q.push(next);
        }
    }
    return cnt == 0;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 790. Domino and Tromino Tiling
Next
[LeetCode] 25. Reverse Nodes in k-Group