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.
idea:
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.
这道题目看能看得懂 但是实际上毫无头绪。
看了看讨论里面的答案找一下头绪
先看自己最喜欢的BFS.
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<>());
map.get(c[0]).add(c[1]);
map.get(c[1]).add(c[0]);
}
Queue<Integer> queue = new LinkedList<>();
queue.offer(0);
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
res++;
}
queue.offer(next);
}
}
return res;
}
}
虽然这道题是让我们找我们需要的最小转换的边的数量。
但是 实际上 为了让所有的边都转向node 0,这个需要转换的边的个数是确定的。
所以我们用hashmap来储存