LeetCode 841:钥匙和房间 Keys and Rooms
题目:
有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。
在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j] 由 [0,1,...,N-1] 中的一个整数表示,其中 N = rooms.length。 钥匙 rooms[i][j] = v 可以打开编号为 v 的房间。
最初,除 0 号房间外的其余所有房间都被锁住。
你可以自由地在房间之间来回走动。
如果能进入每个房间返回 true,否则返回 false。
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.
示例 1:
输入: [[1],[2],[3],[]]
输出: true
解释:
我们从 0 号房间开始,拿到钥匙 1。
之后我们去 1 号房间,拿到钥匙 2。
然后我们去 2 号房间,拿到钥匙 3。
最后我们去了 3 号房间。
由于我们能够进入每个房间,我们返回 true。
示例 2:
输入:[[1,3],[3,0,1],[2],[0]]
输出:false
解释:我们不能进入 2 号房间。
提示:
1 <= rooms.length <= 10000 <= rooms[i].length <= 1000- 所有房间中的钥匙数量总计不超过
3000。
Note:
1 <= rooms.length <= 10000 <= rooms[i].length <= 1000- The number of keys in all rooms combined is at most
3000.
解题思路:
很简单的一道题,从0号房间开始递归遍历就可以了。唯一需要注意的是如何判断房间是否访问过。可以用set哈希表把已访问过的房间号记录下来,最后如果哈希表长度和rooms长度相等,那么就意味着所有房间均可到达。
代码:
Set集合(Java):
class Solution {
Set<Integer> set = new LinkedHashSet<>();
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
helper(rooms, 0);
return set.size() == rooms.size();//长度相等则可以到达所有房间
}
private void helper(List<List<Integer>> rooms, int index) {
if (set.contains(index)) return;
set.add(index);//已访问房间号加入哈希表
for (Integer i : rooms.get(index)) {//遍历房间的每一个钥匙
helper(rooms, i);//进入递归
}
}
}
可以看到用哈希表解题方法在递归期间会多出许多set函数的调用,如 set.add() 、set.contains(),相对很多这道题解题时间,这个开销是很大。对这道题而言,是完全可以用数组避免的。
Java:
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int len = rooms.size();
int[] visited = new int[len];//初始化等长数组,数组每个值默认为0
helper(rooms, 0, visited);
for (int i : visited)
if (i == 0) return false;//数组中依然有0,则证明有房间未访问到
return true;
}
private void helper(List<List<Integer>> rooms, int index, int[] visited) {
if (visited[index] == 1) return;//如果该房间已访问过,直接返回
visited[index] = 1;//在访问过的房间,改为1来标记
for (Integer i : rooms.get(index)) {//遍历
helper(rooms, i, visited);
}
}
}
Python:
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
size=len(rooms)
self.visited = [False]*size # 初始化等长数组,默认为False,所有房间均未访问
self.helper(rooms, 0)
return all(self.visited)
def helper(self, rooms: List[List[int]], index: int) -> None:
if self.visited[index]:#如果为True,该房间已访问过,直接返回
return
self.visited[index] = True #在访问的房间标记为True
for i in rooms[index]:#遍历钥匙
self.helper(rooms, i)#进入递归函数
欢迎关注微.信公.众号:爱写Bug

LeetCode 841:钥匙和房间 Keys and Rooms的更多相关文章
- [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 ...
- 【LeetCode】841. 钥匙和房间
841. 钥匙和房间 知识点:图:递归 题目描述 有 N 个房间,开始时你位于 0 号房间.每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间. 在形式上, ...
- Leetcode-841. 钥匙和房间
题目 有 N 个房间,开始时你位于 0 号房间.每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间. 在形式上,对于每个房间 i 都有一个钥匙列表 room ...
- 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 ...
- leetcode841 Keys and Rooms
""" There are N rooms and you start in room 0. Each room has a distinct number in 0, ...
- [LeetCode] 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 ...
- 【LeetCode】841. Keys and Rooms 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...
- LeetCode 841. Keys and Rooms
原题链接在这里:https://leetcode.com/problems/keys-and-rooms/ 题目: There are N rooms and you start in room 0. ...
- 841. Keys and Rooms —— weekly contest 86
题目链接:https://leetcode.com/problems/keys-and-rooms/description/ 简单DFS time:9ms 1 class Solution { 2 p ...
随机推荐
- SQL Server查询某个表被哪些存储过程调用
问题描述: 今天有个同事问到如何查询某个表被哪些存储过程调用, 然后同事说可以用SQL search查询,自己试了一下确实可以 sqlsearch下载说明地址:https://www.cnblogs. ...
- pytest执行用例时从conftest.py抛出ModuleNotFoundError:No module named 'XXX'异常的解决办法
一.问题描述 在项目根目录下执行整个测试用例,直接从conftest.py模块中抛出了ModuleNotFoundError:No module named 'TestDatas'的异常: 二.解决方 ...
- tf.contrib.slim模块简介
原文连接:https://blog.csdn.net/MOU_IT/article/details/82717745 1.简介 对于tensorflow.contrib这个库,tensorflow官方 ...
- 重磅来袭!Reactive 架构专场四城巡回演讲
Reactive 究竟是什么?Reactive 对架构设计的影响和冲击,以及给开发方式带来的改变有哪些?为什么阿里巴巴.Pivotal.Facebook 纷纷在生产环境中实践 Reactive? 本次 ...
- 数据库——SQL-SERVER CREATE-TABLES
给出数据库实验所需要的“CREATE-TABLES.SQL”文件 use master go if exists (select * from dbo.sysdatabases where name ...
- Web前端基础(8):JavaScript(二)
1. 数据类型转换 1.1 将数值类型转换成字符串类型 1.1.1 隐式转换 在js中,当运算符在运算时,如果两边数据不统一,CPU就无法计算,这时我们编译器会自动将运算符两边的数据做一个数据类型转换 ...
- Java的23种设计模式,详细讲解(三)
本人免费整理了Java高级资料,涵盖了Java.Redis.MongoDB.MySQL.Zookeeper.Spring Cloud.Dubbo高并发分布式等教程,一共30G,需要自己领取.传送门:h ...
- SpringBoot(八) SpringBoot整合Kafka
window下安装kafka和zooker,超详细:https://blog.csdn.net/weixin_33446857/article/details/81982455 kafka:安装下载教 ...
- PHP odbc_errormsg ODBC 函数
定义和用法 odbc_errormsg - 获取最后一条错误消息 语法 odbc_errormsg ( [ resource $connection_id ] ) 返回包含最后一个ODBC错误消息的字 ...
- CSS3 3D变形 transform---rotateX(), rotateY(), rotateZ(), 透视(perspective)
2d x y 3d x y z 左手坐标系 伸出左手,让拇指和食指成“L”形,大拇指向右,食指向上,中指指向前方.这样我们就建立了一个左手坐标系,拇指.食指和中指分别代表X.Y.Z轴的正方向.如下图 ...