zoukankan      html  css  js  c++  java
  • 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

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    有限制的最大连续和问题
    Codevs 5056 潜水员
    Codevs 1958 刺激
    Codevs 3731 寻找道路 2014年 NOIP全国联赛提高组
    [NOIP2014]解方程
    Codevs 3729 飞扬的小鸟
    Codevs 1689 建造高塔
    Codevs 2102 石子归并 2
    C语言基础之进制的那些事(1)
    指针
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12741135.html
Copyright © 2011-2022 走看看