841. Keys and Rooms —— weekly contest 86

Posted 又啦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了841. Keys and Rooms —— weekly contest 86相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/keys-and-rooms/description/

简单DFS

time:9ms

 1 class Solution {
 2 public:
 3     void DFS(int root,vector<int>& visited,vector<vector<int>>& rooms){
 4         visited[root] = 1;
 5         for(auto x : rooms[root]){
 6             if(visited[x] == 0){
 7                 DFS(x,visited,rooms);
 8             }
 9         }
10     }
11     bool canVisitAllRooms(vector<vector<int>>& rooms) {
12         vector<int> visited;
13         int n = rooms.size();
14         visited.assign(n,0);
15         DFS(0,visited,rooms);
16         for(int i = 0; i < n; i++){
17             if(visited[i] == 0){
18                 return false;
19             }
20         }
21         return true;
22     }
23     
24 };

看到别人的用堆栈实现的dfs也贴一下

 1  bool canVisitAllRooms(vector<vector<int>>& rooms) {
 2         stack<int> dfs; dfs.push(0);
 3         unordered_set<int> seen = {0};
 4         while (!dfs.empty()) {
 5             int i = dfs.top(); dfs.pop();
 6             for (int j : rooms[i])
 7                 if (seen.count(j) == 0) {
 8                     dfs.push(j);
 9                     seen.insert(j);
10                     if (rooms.size() == seen.size()) return true;
11                 }
12         }
13         return rooms.size() == seen.size();
14     }

出处:https://leetcode.com/problems/keys-and-rooms/discuss/133855/Straight-Forward

以上是关于841. Keys and Rooms —— weekly contest 86的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 841:钥匙和房间 Keys and Rooms

leetcode.841钥匙和房间

leetcode 841:钥匙和房间

CodeForces 519E A and B and Lecture Rooms(倍增)

286 walls and gate最近的出口

A and B and Lecture Rooms(LCA)