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

posted @ 2018-05-27 23:41  又啦  阅读(142)  评论(0编辑  收藏  举报