841. Keys and Rooms

// // Created by YUQIONG LI on 16/9/2018. // #include <iostream> #include <vector> #include <stack> using std::vector; using std::stack; using std::find; using std::cout; using std::endl; class Solution { public: bool canVisitAllRooms(vector<vector<int>>& rooms) { int numRooms = rooms.size(); vector<int> res; stack<int> s; s.push(0); vector<int> visited; while (!s.empty()){ // try a preorder -- simple int curr = s.top(); s.pop(); if (find(visited.begin(), visited.end(), curr) == visited.end()){ // not see this node before res.push_back(curr); visited.push_back(curr); for (auto & neighbor : rooms[curr]){ if (find(visited.begin(), visited.end(), neighbor) == visited.end()){ s.push(neighbor); } } } } return res.size() == rooms.size(); } }; int main(){ vector< vector<int> > rooms = {{1,3},{3,0,1},{2},{0}}; Solution s; cout << s.canVisitAllRooms(rooms) << endl; return 0; }
Switched to pre-order traversal and solved it.
With post-order, it's hard to know where to put that res.push_back(curr) statement.

Reference for DFS:
http://www.mathcs.emory.edu/~cheung/Courses/171/Syllabus/11-Graph/dfs.html

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.