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