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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    TypeError: Buffer.alloc is not a function
    node.js服务端程序在Linux上持久运行
    C#中的反射
    群要事日记
    vs2017 自定义生成规则 错误 MSB3721 命令 ”已退出,返回代码为 1。
    VP9 Video Codec
    用户手册是Yasm汇编
    更改Mysql数据库存储位置
    注册表项
    C#开发可以可视化操作的windows服务
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12741135.html
Copyright © 2011-2022 走看看