昌平企业网站建设信阳网站推广公司
1466. 重新规划路线
中等
n
座城市,从 0
到 n-1
编号,其间共有 n-1
条路线。因此,要想在两座不同城市之间旅行只有唯一一条路线可供选择(路线网形成一颗树)。去年,交通运输部决定重新规划路线,以改变交通拥堵的状况。
路线用 connections
表示,其中 connections[i] = [a, b]
表示从城市 a
到 b
的一条有向路线。
今年,城市 0 将会举办一场大型比赛,很多游客都想前往城市 0 。
请你帮助重新规划路线方向,使每个城市都可以访问城市 0 。返回需要变更方向的最小路线数。
题目数据 保证 每个城市在重新规划路线方向后都能到达城市 0 。
示例 1:
输入:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
输出:3
解释:更改以红色显示的路线的方向,使每个城市都可以到达城市 0 。
示例 2:
输入:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
输出:2
解释:更改以红色显示的路线的方向,使每个城市都可以到达城市 0 。
示例 3:
输入:n = 3, connections = [[1,0],[2,0]]
输出:0
提示:
2 <= n <= 5 * 10^4
connections.length == n-1
connections[i].length == 2
0 <= connections[i][0], connections[i][1] <= n-1
connections[i][0] != connections[i][1]
BFS
class Solution {/**构件图时标志是正边还是反边,一次bfs如果是反边则需要res+1*/List<int[]>[] g;public int minReorder(int n, int[][] connections) {g = new ArrayList[n];Arrays.setAll(g, e -> new ArrayList<int[]>());for(int[] c : connections){int x = c[0], y = c[1];g[x].add(new int[]{y, -1}); // 1标志正边,-1标志反边g[y].add(new int[]{x, 1});}boolean[] vis = new boolean[n];Deque<Integer> dq = new ArrayDeque<>();dq.add(0);vis[0] = true;int res = 0;while(!dq.isEmpty()){int x = dq.pollLast();for(int[] q : g[x]){int y = q[0], dir = q[1];if(vis[y]) continue;vis[y] = true;if(dir == -1) res += 1;dq.addFirst(y);}}return res;}
}
DFS
class Solution { List<int[]>[] g;int res = 0;boolean[] vis;public int minReorder(int n, int[][] connections) {g = new ArrayList[n];Arrays.setAll(g, e -> new ArrayList<int[]>());for(int[] c : connections){int x = c[0], y = c[1];g[x].add(new int[]{y, -1}); // 1标志正边,-1标志反边g[y].add(new int[]{x, 1});}vis = new boolean[n];dfs(0, -1);return res;}public void dfs(int x, int fa){vis[x] = true;for(int[] q : g[x]){int y = q[0], dir = q[1];if(vis[y]) continue;if(dir == -1) res += 1;dfs(y, x);}}
}