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 rooms[i] 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 <= rooms[i].length <= 1000

1 <= sum(rooms[i].length) <= 3000

0 <= rooms[i][j] < n

All the values of rooms[i] 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;
    }
};
相关推荐
白总Server17 分钟前
GaussDB 分布式数据库调优(架构到全链路优化)
java·网络·c++·架构·go·scala·数据库架构
whoarethenext1 小时前
C++/OpenCV地砖识别系统结合 Libevent 实现网络化 AI 接入
c++·人工智能·opencv
Antonio9151 小时前
【Linux】Linux基础I/O
linux·c++
虾球xz1 小时前
CppCon 2015 学习:C++ devirtualization in clang
开发语言·c++·学习
@解忧杂货铺1 小时前
基于用户的协同过滤推荐算法实现(Java电商平台)
算法·机器学习·推荐算法
呆呆的小鳄鱼1 小时前
IO之详解cin(c++IO关键理解)
linux·c语言·c++
爱coding的橙子1 小时前
每日算法刷题Day31 6.14:leetcode二分答案2道题,结束二分答案,开始枚举技巧,用时1h10min
算法·leetcode·职场和发展
@ chen1 小时前
龟兔赛跑算法(Floyd‘s Cycle-Finding Algorithm)寻找重复数
算法
晨曦学习日记1 小时前
leetcode题解538:把二叉搜索树转换为累加树
算法
孟大本事要学习1 小时前
算法第13天|继续学习二叉树:平衡二叉树(递归)、二叉树所有路径(递归)、左叶子之和(递归)
学习·算法