LeetCode 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] = [a, b] represents a road from city a to b.

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 the city 0 after reorder.

even though it said some much on the problem description, the meaning of this question is pretty clear.
the graph we are given is a graph that like a line, but the directed is not the same for every node. so the graph is something like this:

the node of 0 can be in the head, or in the middle, so we are asking the minimum number of edges directions we are gonna change in order to let any city can go to node 0.

这道题目看能看得懂 但是实际上毫无头绪。

class Solution {
    public int minReorder(int n, int[][] connections) {
		HashSet<String> set = new HashSet<>();
        HashMap<Integer, HashSet<Integer>> map = new HashMap<>(); //node and its neighbors
        for (int[] c: connections) {
            set.add(c[0] + "," + c[1]); //set contains the edges, it has to contains all nodes and the direction, so we use hashset
            map.computeIfAbsent(c[0], k -> new HashSet<>()); //
            map.computeIfAbsent(c[1], k -> new HashSet<>());
        Queue<Integer> queue = new LinkedList<>();
        boolean[] visited = new boolean[n];
        visited[0] = true;
        int res = 0;
        while (!queue.isEmpty()) {
            int cur = queue.poll();
            for (int next: map.get(cur)) { //get all the neighbor of cur
                if (visited[next]) continue; //if visited, just move to next
                visited[next] = true; //marked it as visited
                if (!set.contains(next + "," + cur)) { //if this edge doesn't contains in the set
        return res;

但是 实际上 为了让所有的边都转向node 0,这个需要转换的边的个数是确定的。

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页