841. Keys and Rooms

Problem:

There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room.

Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length. A key rooms[i][j] = v opens the room with number v.

Initially, all the rooms start locked (except for room 0).

You can walk back and forth between rooms freely.

Return true if and only if you can enter every room.

Example 1:

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

Example 2:

Input: [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can't enter the room with number 2.

Note:

  1. 1 <= rooms.length <= 1000
  2. 0 <= rooms[i].length <= 1000
  3. The number of keys in all rooms combined is at most 3000.

思路

Solution (C++):

bool canVisitAllRooms(vector<vector<int>>& rooms) {
    stack<int> dfs;
    dfs.push(0);
    unordered_set<int> visited{0};
    while (!dfs.empty()) {
        int i = dfs.top();
        dfs.pop();
        for (auto j : rooms[i]) {
            if (visited.count(j) == 0) {
                dfs.push(j);
                visited.insert(j);
                if (visited.size() == rooms.size())
                    return true;
            }
        }
    }
    return rooms.size() == visited.size();
}

性能

Runtime: 12 ms  Memory Usage: 8.7 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

原文链接: https://www.cnblogs.com/dysjtu1995/p/12741135.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    841. Keys and Rooms

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/343404

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午2:06
下一篇 2023年3月2日 上午2:06

相关推荐