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.

这道题给了我们一些房间,房间里有一些钥匙,用钥匙可以打开对应的房间,说是起始时在房间0,问最终是否可以打开所有的房间。这不由得让博主想起了惊悚片《万能钥匙》,还真是头皮发麻啊。赶紧扯回来,这是一道典型的有向图的遍历的题,邻接链表都已经建立好了,这里直接遍历就好了,这里先用 BFS 来遍历。使用一个 HashSet 来记录访问过的房间,先把0放进去,然后使用 queue 来辅助遍历,同样将0放入。之后进行典型的 BFS 遍历,取出队首的房间,然后遍历其中的所有钥匙,若该钥匙对应的房间已经遍历过了,直接跳过,否则就将钥匙加入 HashSet。此时看若 HashSet 中的钥匙数已经等于房间总数了,直接返回 true,因为这表示所有房间已经访问过了,否则就将钥匙加入队列继续遍历。最后遍历结束后,就看 HashSet 中的钥匙数是否和房间总数相等即可,参见代码如下:

解法一:

class Solution {
public:
bool canVisitAllRooms(vector<vector<int>>& rooms) {
unordered_set<int> visited{{}};
queue<int> q{{}};
while (!q.empty()) {
int t = q.front(); q.pop();
for (int key : rooms[t]) {
if (visited.count(key)) continue;
visited.insert(key);
if (visited.size() == rooms.size()) return true;
q.push(key);
}
}
return visited.size() == rooms.size();
}
};

我们也可以使用递归的解法来做,还是使用 HashSet 来记录访问过的房间,递归函数还需要传进当前的房间,还有 HashSet,首先将当前房间加入 HashSet,然后遍历此房间中的所有钥匙,如果其对应的房间没有访问过,则调用递归函数,参见代码如下:

解法二:

class Solution {
public:
bool canVisitAllRooms(vector<vector<int>>& rooms) {
unordered_set<int> visited;
helper(rooms, , visited);
return visited.size() == rooms.size();
}
void helper(vector<vector<int>>& rooms, int cur, unordered_set<int>& visited) {
visited.insert(cur);
for (int key : rooms[cur]) {
if (!visited.count(key)) helper(rooms, key, visited);
}
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/841

参考资料:

https://leetcode.com/problems/keys-and-rooms/

https://leetcode.com/problems/keys-and-rooms/discuss/133944/Java-8-lines

https://leetcode.com/problems/keys-and-rooms/discuss/133855/Straight-Forward

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Keys and Rooms 钥匙与房间的更多相关文章

  1. 【LeetCode】841. 钥匙和房间

    841. 钥匙和房间 知识点:图:递归 题目描述 有 N 个房间,开始时你位于 0 号房间.每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间. 在形式上, ...

  2. Leetcode-841. 钥匙和房间

    题目 有 N 个房间,开始时你位于 0 号房间.每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间. 在形式上,对于每个房间 i 都有一个钥匙列表 room ...

  3. [LeetCode] 253. Meeting Rooms II 会议室 II

    Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si ...

  4. LC 841. Keys and Rooms

    There are N rooms and you start in room 0.  Each room has a distinct number in 0, 1, 2, ..., N-1, an ...

  5. LeetCode 841:钥匙和房间 Keys and Rooms

    题目: ​ 有 N 个房间,开始时你位于 0 号房间.每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间. ​ 在形式上,对于每个房间 i 都有一个钥匙列表 ...

  6. [Swift]LeetCode841. 钥匙和房间 | Keys and Rooms

    There are N rooms and you start in room 0.  Each room has a distinct number in 0, 1, 2, ..., N-1, an ...

  7. 【LeetCode】841. Keys and Rooms 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...

  8. [LeetCode] 864. Shortest Path to Get All Keys 获得所有钥匙的最短路径

    We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@& ...

  9. LeetCode 841. Keys and Rooms

    原题链接在这里:https://leetcode.com/problems/keys-and-rooms/ 题目: There are N rooms and you start in room 0. ...

随机推荐

  1. Web项目容器集成ActiveMQ & SpringBoot整合ActiveMQ

    集成tomcat就是随项目启动而启动tomcat,最简单的方法就是监听器监听容器创建之后以Broker的方式启动ActiveMQ. 1.web项目中Broker启动的方式进行集成 在这里采用Liste ...

  2. 使用scrapy爬虫,爬取今日头条搜索吉林疫苗新闻(scrapy+selenium+PhantomJS)

    这一阵子吉林疫苗案,备受大家关注,索性使用爬虫来爬取今日头条搜索吉林疫苗的新闻 依然使用三件套(scrapy+selenium+PhantomJS)来爬取新闻 以下是搜索页面,得到吉林疫苗的搜索信息, ...

  3. nginx跨域问题记录

    现象:访问 toolbox.chinasoft.com 提示如下:Access to Font at 'https://images.chinasoft.com/static-toolbox/styl ...

  4. Mongodb 安装错误汇总

    Failed to restart mongod.service: Unit mongod.service not found. 解决方法: Most probably unit mongodb.se ...

  5. Google 以 Flutter 作为原生突破口,移动端即将统一了

    Android 的前生今世 Android 系统 Android系统作为全球第一大系统,基于 Java 开发的移动端有着诸多的性能优势. 2018年前 H5 的性能瓶颈和 RN 的停更 导致业界对跨平 ...

  6. uni-app 引入本地iconfont的正确姿势以及阿里图标引入

    1.引入本地iconfont iconfont文件里面包含 iconfont.ttf.iconfont.css, 将 iconfont.tt64文件转位 base64.推荐转换工具地址:https:/ ...

  7. shell实用

    nginx日志切割 [root@localhost ~]# vim /opt/fenge.sh #!/bin/bash #Filename:fenge.sh d=$(date -d "-1 ...

  8. TCP和UDP的区别以及使用python服务端客户端简单编程

    一.TCP.UDP区别总结 1.TCP面向连接(如打电话要先拨号建立连接):UDP是无连接的,即发送数据之前不需要建立连接 2.TCP提供可靠的服务,也就是说,通过TCP连接传送的数据,无差错,不丢失 ...

  9. JavaScript复制文本探究

    JS复制文本基本分为两步-First: 选中需要复制的节点,及选区:Second: 执行document.execCommand('copy')命令复制 对于选区,属于HTMLInputElement ...

  10. Nuxt.js国际化vue-i18n的搭配使用

    Nuxt.js国际化的前提是,已经使用脚手架工具搭建好了Nuxt.js的开发环境. 我使用的环境是nuxt@2.3 + vuetify@1.4 + vue-i18n@7.3 1. 先安装vue-i18 ...