[leetcode] 1466. Reorder Routes to Make All Paths Lead to the City Zero _ Algorithm Problem Solve for python



1. Problem

1466. Reorder Routes to Make All Paths Lead to the City Zero

There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.

Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.

This year, there will be a big event in the capital (city 0), and many people want to travel to this city.

Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.

It’s guaranteed that each city can reach city 0 after reorder.

Example 1:

Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).

Example 2:

Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).

Example 3:

Input: n = 3, connections = [[1,0],[2,0]]
Output: 0

Constraints:

  • 2 <= n <= 5 * 104
  • connections.length == n - 1
  • connections[i].length == 2
  • 0 <= ai, bi <= n - 1
  • ai != bi

2. Solution

I solved this problem like this.

  • I check real edge and virtual edge.
  • Since there are n-1 connections, if you check from 0, you have to access every edge exactly once.
  • Starting from 0, use deque to check the edges going to the next node.
    • In order not to change direction, the edge of the popped node must not be in the dic.
    • To change direction, the edge of the popped node must be in the dic.
class Solution:
    def minReorder(self, n: int, connections: List[List[int]]) -> int:
        dic = {}
        opposite_dic = {}

        for c in connections:
            fromm, to = c[0], c[1]
            if fromm not in dic:
                dic[fromm] = []
            dic[fromm].append(to)
            if to not in opposite_dic:
                opposite_dic[to] = []
            opposite_dic[to].append(fromm)
        
        deq = deque([0])
        ans = 0
        is_visited = [False] * n
        while deq:
            node = deq.popleft()
            if is_visited[node]:
                continue
            is_visited[node] = True

            real_nodes = dic[node] if node in dic else []
            for next_node in real_nodes:
                if is_visited[next_node] == False:
                    deq.append(next_node)
                    ans += 1

            op_nodes = opposite_dic[node] if node in opposite_dic else []
            for next_node in op_nodes:
                if is_visited[next_node] == False:
                    deq.append(next_node)

        return ans