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;
    }
};
相关推荐
Tim_1015 分钟前
【算法专题训练】20、LRU 缓存
c++·算法·缓存
Vect__29 分钟前
从零实现一个简化版string 类 —— 深入理解std::string的底层设计
c++
hope_wisdom32 分钟前
C/C++数据结构之栈基础
c语言·数据结构·c++··stack
ajassi200040 分钟前
开源 C++ QT Widget 开发(十四)多媒体--录音机
linux·c++·qt·开源
Lris-KK1 小时前
【Leetcode】高频SQL基础题--1341.电影评分
sql·leetcode
B612 little star king1 小时前
力扣29. 两数相除题解
java·算法·leetcode
野犬寒鸦1 小时前
力扣hot100:环形链表(快慢指针法)(141)
java·数据结构·算法·leetcode·面试·职场和发展
时光追逐者1 小时前
C# 哈希查找算法实操
算法·c#·哈希算法
Jasmine_llq1 小时前
《P3825 [NOI2017] 游戏》
算法·游戏·枚举法·2-sat 算法·tarjan 算法·邻接表存储
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 38: 二叉树的锯齿形层序遍历、二叉树最大宽度
java·linux·运维·算法·leetcode·链表·职场和发展