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

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.

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.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;
}
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

Tech In Pieces

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

06-15 65
11-28 22
06-27 266
01-31 263