diff --git a/src/graphs/reorder_routes_to_make_all_paths_lead_to_the_city_zero/__init__.py b/src/graphs/reorder_routes_to_make_all_paths_lead_to_the_city_zero/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/graphs/reorder_routes_to_make_all_paths_lead_to_the_city_zero/solution.py b/src/graphs/reorder_routes_to_make_all_paths_lead_to_the_city_zero/solution.py new file mode 100644 index 0000000..cb5e01c --- /dev/null +++ b/src/graphs/reorder_routes_to_make_all_paths_lead_to_the_city_zero/solution.py @@ -0,0 +1,24 @@ +class Solution: + def dfs( + self, + adjacent: list[list[tuple[int, int]]], + visited: list[bool], + current_city: int, + ) -> int: + visited[current_city] = True + changes = 0 + for neighbour, direction in adjacent[current_city]: + if not visited[neighbour]: + if direction == 1: + changes += 1 + changes += self.dfs(adjacent, visited, neighbour) + + return changes + + def minReorder(self, n: int, connections: list[list[int]]) -> int: + adjacent = [[] for _ in range(n)] + for u, v in connections: + adjacent[u].append((v, 1)) + adjacent[v].append((u, -1)) + visited = [False] * n + return self.dfs(adjacent, visited, 0) diff --git a/tests/test_reorder_routes_to_make_all_paths_lead_to_the_city_zero.py b/tests/test_reorder_routes_to_make_all_paths_lead_to_the_city_zero.py new file mode 100644 index 0000000..126ebb7 --- /dev/null +++ b/tests/test_reorder_routes_to_make_all_paths_lead_to_the_city_zero.py @@ -0,0 +1,17 @@ +import pytest +from src.graphs.reorder_routes_to_make_all_paths_lead_to_the_city_zero.solution import ( + Solution, +) + + +@pytest.mark.parametrize( + "n, connections, expected", + [ + (6, [[0, 1], [1, 3], [2, 3], [4, 0], [4, 5]], 3), + (5, [[1, 0], [1, 2], [3, 2], [3, 4]], 2), + (3, [[1, 0], [2, 0]], 0), + ], +) +def test_min_reorder(n, connections, expected): + solution = Solution() + assert solution.minReorder(n, connections) == expected