LeetCode C++ 841. Keys and Rooms【BFS/DFS】中等
发布日期:2021-07-01 02:50:50
浏览次数:3
分类:技术文章
本文共 1591 字,大约阅读时间需要 5 分钟。
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: trueExplanation: 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: falseExplanation: We can't enter the room with number 2.
Note:
1 <= rooms.length <= 1000
0 <= rooms[i].length <= 1000
- The number of keys in all rooms combined is at most
3000
.
题意:N
个房间,开始位于 0
号房间,每个房间有一些钥匙可以进入其他房间。判断是否能够进入每个房间。
思路:DFS一遍过。这个中等题太简单了。代码如下:
class Solution { public: vectorvisited; void dfs(const vector > &rooms, int idx) { visited[idx] = true; for (const int key : rooms[idx]) if (!visited[key]) dfs(rooms, key); } bool canVisitAllRooms(vector >& rooms) { if (rooms.size() <= 1) return true; visited.resize(rooms.size()); dfs(rooms, 0); for (const bool f : visited) if (!f) return false; return true; }};
转载地址:https://memcpy0.blog.csdn.net/article/details/108332970 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月19日 06时23分15秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
实时开发框架Meteor 实际应用系列<一>---文件的上传和下载[补充]
2019-05-03
实时开发框架Meteor API解读系列<七> Collection --01
2019-05-03
启用fcitx-qimpanel面板程序
2021-07-06
浅谈Q的基本实现
2021-07-06
iOS开发——cache自动清理方案探索
2021-07-06
阿里云短信服务(JAVA)
2021-07-06
std::exception标准和各平台实现的不同
2021-07-06
C++的匿名对象
2021-07-06
C++中class和typename的区别
2021-07-06
C++常量表达式、const、constexpr(C++11新增)的区别
2021-07-06
Windows和Linux进程与线程的区别
2021-07-06
Windows下C++多线程编程(入门实例)
2021-07-06
宽字符标量L"xx"在VC6.0/7.0和GNU g++中的不同实现。
2021-07-06
VS工程属性“字符集”和源文件“高级保存选项”字符集区别
2021-07-06
Linux下C++多线程编程(入门实例)
2021-07-06
深入理解HashMap
2021-07-06
[arr firstObject] 和 arr[0] 的区别
2021-07-06
求解最大子列和问题——MaxSubSum
2021-07-06
iOS9新特性之常见关键字
2021-07-06
iOS中 单例设计模式 的使用方法
2021-07-06