Skip to content

Commit af3fb4a

Browse files
authored
Create 1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.cpp
1 parent 6e5b69b commit af3fb4a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
int minReorder(int n, vector<vector<int>>& connections) {
4+
unordered_map<int, vector<pair<int, bool>>> graph;
5+
unordered_set<int> visited;
6+
7+
for (int i = 0; i < n; i++)
8+
graph[i] = vector<pair<int, bool>>{};
9+
10+
for (vector<int> connection : connections) {
11+
graph[connection[0]].push_back(make_pair(connection[1], true));
12+
graph[connection[1]].push_back(make_pair(connection[0], false));
13+
}
14+
15+
int cnt = 0;
16+
stack<int> stk;
17+
stk.push(0);
18+
visited.insert(0);
19+
20+
while (!stk.empty()) {
21+
int u = stk.top();
22+
stk.pop();
23+
for (pair<int, bool> v : graph[u]) {
24+
if (visited.count(v.first))
25+
continue;
26+
stk.push(v.first);
27+
visited.insert(v.first);
28+
if (v.second)
29+
cnt += 1;
30+
}
31+
}
32+
33+
return cnt;
34+
}
35+
};
36+

0 commit comments

Comments
 (0)