841. Keys and Rooms —— weekly contest 86
阿新 • • 發佈:2018-05-28
ted blank order IV sig for set div and
題目鏈接: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