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;
    }
};
相关推荐
自信1504130575913 分钟前
初学者小白复盘15之指针(4)
c语言·数据结构·算法
郝学胜-神的一滴13 分钟前
Cesium绘制线:从基础到高级技巧
前端·javascript·程序人生·线性代数·算法·矩阵·图形渲染
AA陈超21 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-13 属性菜单 - 边框值
c++·游戏·ue5·游戏引擎·虚幻
东皇太星1 小时前
机器学习概念,算法原理及应用
算法·机器学习·梯度下降法
.格子衫.1 小时前
021数据结构之并查集——算法备赛
数据结构·算法
姝孟1 小时前
C++学习——类与对象详细知识点总结
c++·笔记·学习
im_AMBER1 小时前
Leetcode 35
笔记·学习·算法·leetcode
码农多耕地呗1 小时前
力扣101.对称二叉树(java)
算法·leetcode
小龙报1 小时前
《算法通关指南之C++编程篇(5)----- 条件判断与循环(下)》
c语言·开发语言·c++·算法·visualstudio·学习方法·visual studio
郝学胜-神的一滴1 小时前
C++ STL(标准模板库)深度解析:从基础到实践
linux·服务器·开发语言·c++·算法