1466. Reorder Routes to Make All Paths Lead to the City Zero
DFS
class Solution:
def __init__(self):
self.res = 0
self.visited = set()
def minReorder(self, n: int, connections: List[List[int]]) -> int:
fromWhere = {_:[] for _ in range(n)}
goWhere = {_:[] for _ in range(n)}
for i, j in connections:
fromWhere[j].append(i)
goWhere[i].append(j)
def correct(city):
self.visited.add(city)
for c in fromWhere[city]:
if c not in self.visited:
correct(c)
for c in goWhere[city]:
if c not in self.visited:
self.res += 1
correct(c)
correct(0)
return self.res
Last updated
Was this helpful?