leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
1466.cpp (863B)
0 class Solution { 1 public: 2 int minReorder(int n, vector<vector<int>> &connections) { 3 unordered_set<string> us; 4 vector<bool> visited(n, false); 5 vector<vector<int>> adj(n, vector<int>()); 6 7 for (auto &e : connections) { 8 us.insert(to_string(e[0]) + " " + to_string(e[1])); 9 adj[e[0]].push_back(e[1]); 10 adj[e[1]].push_back(e[0]); 11 } 12 13 int res = 0; 14 15 stack<int> st; 16 st.push(0); 17 visited[0] = true; 18 while (!st.empty()) { 19 int root = st.top(); 20 st.pop(); 21 for (auto c : adj[root]) 22 if (!visited[c]) { 23 if (!us.count(to_string(c) + " " + to_string(root))) res++; 24 visited[c] = true; 25 st.push(c); 26 } 27 } 28 return res; 29 } 30 };