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;
    }
};
相关推荐
程序员Xu21 分钟前
【OD机试题解法笔记】连续出牌数量
笔记·算法·深度优先
CoovallyAIHub34 分钟前
单目深度估计重大突破:无需标签,精度超越 SOTA!西湖大学团队提出多教师蒸馏新方案
深度学习·算法·计算机视觉
CoovallyAIHub37 分钟前
从FCOS3D到PGD:看深度估计如何快速搭建你的3D检测项目
深度学习·算法·计算机视觉
偷偷的卷1 小时前
【算法笔记 day three】滑动窗口(其他类型)
数据结构·笔记·python·学习·算法·leetcode
北京地铁1号线1 小时前
Zero-Shot(零样本学习),One-Shot(单样本学习),Few-Shot(少样本学习)概述
人工智能·算法·大模型
大白的编程日记.1 小时前
【计算机基础理论知识】C++篇(二)
开发语言·c++·学习
C语言小火车1 小时前
野指针:C/C++内存管理的“幽灵陷阱”与系统化规避策略
c语言·c++·学习·指针
凤年徐2 小时前
【数据结构】时间复杂度和空间复杂度
c语言·数据结构·c++·笔记·算法
kualcal2 小时前
代码随想录17|二叉树的层序遍历|翻转二叉树|对称二叉树
数据结构·算法
踏莎行hyx2 小时前
使用langchain连接llama.cpp部署的本地deepseek大模型开发简单的LLM应用
c++·ai·langchain·大模型·llama.cpp·deepseek