Skip to content

Commit 205425a

Browse files
1466: Reorder Routes
Reorder Routes to Make All Paths Lead to the City Zero
1 parent 53bb263 commit 205425a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/description/
2+
# T: O(N) where N is the number of nodes in the graph
3+
# S: O(N) where N is the number of nodes in the graph
4+
5+
class Solution:
6+
def __init__(self):
7+
self.reorders = 0
8+
9+
def minReorder(self, n, connections):
10+
edges = {(u, v) for u, v in connections}
11+
graph = {i:[] for i in range(n)}
12+
for u, v in connections:
13+
graph[u].append(v)
14+
graph[v].append(u)
15+
visit = set()
16+
visit.add(0)
17+
def dfs(graph, edges, visit, city):
18+
for node in graph[city]:
19+
if node in visit:
20+
continue
21+
if (node, city) not in edges:
22+
self.reorders+=1
23+
visit.add(node)
24+
dfs(graph, edges, visit, node)
25+
dfs(graph, edges, visit, 0)
26+
return self.reorders

0 commit comments

Comments
 (0)