[Leetcode][BFS]1466.Reorder Routes to Make All Paths Lead to the City Zero

165 阅读1分钟

Description:

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).

Solution: Editorial Solution

Because we need to bring everyone to node 0, we can model the graph as a tree rooted at node 0. So what do we need to do is fliping every edge parent -> child to child -> parent.

image.png

It is more convinient to use BFS. To every edge, we should transform it to two states. for example, [0, 1] -> [0, out], [1, in]. if we found some node has one edge which state is out and the node is not visited, it indicates that the edge is from current node to its child, so we need to flip this edge.

fun minReorder(n: Int, connections: Array<IntArray>): Int {
    val adj = mutableMapOf<Int, MutableList<IntArray>>()
    // transform edge to the states of two nodes
    // state 0: out, state 1: in
    connections.forEach {
        if (adj.containsKey(it[0])) {
            adj[it[0]]!!.add(intArrayOf(it[1], 0))
        } else {
            adj[it[0]] = mutableListOf(intArrayOf(it[1], 0))
        }

        if (adj.containsKey(it[1])) {
            adj[it[1]]!!.add(intArrayOf(it[0], 1))
        } else {
            adj[it[1]] = mutableListOf(intArrayOf(it[0], 1))
        }
    }

    var count = 0
    val visited = IntArray(n){0}
    val queue = LinkedList<Int>()
    queue.add(0)
    visited[0] = -1
    while (queue.isNotEmpty()) {
        // current node
        val node = queue.poll()
        val list = adj[node]
        list!!.forEach {
            // as we use BFS, if the node has not visited, it must be the child of current node.
            if (visited[it[0]] != -1) {
                visited[it[0]] = -1
                if (it[1] == 0) {
                    count++
                }
                queue.add(it[0])
            }
        }
    }
    return count
}