1466. 重新规划路线

1466. 重新规划路线

解法一: dfs

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
func minReorder(n int, connections [][]int) int {
roads := make([][]int, n)
for _, connection := range connections {
roads[connection[0]] = append(roads[connection[0]], -connection[1])
roads[connection[1]] = append(roads[connection[1]], connection[0])
}
ans := 0
var dfs func (start, parent int)
dfs = func (start, parent int) {
for _, road := range roads[start] {
if abs(road) == parent {
continue
}
if road < 0 {
ans++
road = -road
}
dfs(road, start)
}
}
dfs(0, 0)
return ans
}

func abs(num int) int {
if num >= 0 {
return num
}
return -num
}
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int minReorder(int n, int[][] connections) {
List<int[]>[] roads = new ArrayList[n];
for (int i = 0; i < n; i++) {
roads[i] = new ArrayList<>();
}
for (int[] connection : connections) {
roads[connection[0]].add(new int[]{connection[1], 1});
roads[connection[1]].add(new int[]{connection[0], 0});
}
return this.dfs(0, -1, roads);
}

private int dfs(int start, int parent, List<int[]>[] roads) {
int ans = 0;
for (int[] road : roads[start]) {
if (road[0] == parent) {
continue;
}
ans += road[1] + this.dfs(road[0], start, roads);
}
return ans;
}

}
作者

wuhunyu

发布于

2023-12-07

更新于

2023-12-07

许可协议