LeetCode841. Keys and Rooms

文章目录

一、题目

There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.

Given an array rooms where roomsi is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.

Example 1:

Input: rooms = \[1,2,3,\[\]]

Output: true

Explanation:

We visit room 0 and pick up key 1.

We then visit room 1 and pick up key 2.

We then visit room 2 and pick up key 3.

We then visit room 3.

Since we were able to visit every room, we return true.

Example 2:

Input: rooms = \[1,3,3,0,1,2,0]

Output: false

Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.

Constraints:

n == rooms.length

2 <= n <= 1000

0 <= roomsi.length <= 1000

1 <= sum(roomsi.length) <= 3000

0 <= roomsij < n

All the values of roomsi are unique.

二、题解

cpp 复制代码
class Solution {
public:
    void dfs(vector<vector<int>>& rooms,vector<bool>& visited,int key){
        if(visited[key]) return;
        visited[key] = true;
        vector<int> keys = rooms[key];
        for(int i = 0;i < keys.size();i++){
            dfs(rooms,visited,keys[i]);
        }
    }
    bool canVisitAllRooms(vector<vector<int>>& rooms) {
        vector<bool> visited(rooms.size(),false);
        dfs(rooms,visited,0);
        for(int i = 0;i < visited.size();i++){
            if(visited[i] == false) return false;
        }
        return true;
    }
};
相关推荐
Herbert_hwt几秒前
【C语言基础】常量、选择结构与运算符全解析
c语言·开发语言·算法
buhuizhiyuci4 分钟前
【Linux 篇】数字世界的水流蓄水池 —— IO 缓冲区机制深度实战解析
linux·运维·服务器·c++
Suxing932 分钟前
C语言基础分享:从“租房”到“拆迁”,C语言动态内存管理
java·数据结构·算法
啦啦啦啦啦zzzz36 分钟前
moduo网络库 Acceptor TcpConnection
服务器·网络·c++·reactor·网络库
键盘会跳舞38 分钟前
C++:右值引用与移动语义源码级深度拆解——现代C++性能优化的语言基石
c++·右值引用·移动语义
码匠许师傅1 小时前
【C++ 面试真题】聊聊 C++ 的虚函数和多态
java·c++·面试
LuminousCPP1 小时前
单链表专题(四)-刷题复盘篇-LeetCode 138 随机链表复制|原地拷贝法突破复杂指针操作
数据结构·笔记·算法·leetcode·链表
逆境不可逃1 小时前
【LeetCode 912】排序数组——随机化快速排序详解
数据结构·算法·排序算法
Coder-magician1 小时前
《代码随想录》刷题打卡day31:动态规划-背包问题part02
算法·动态规划
薛定e的猫咪1 小时前
从因果视角解决多智能体协作:细读 SCIC 算法
算法