1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/go/reorder-routes-to-make-all-paths-lead-to-the-city-zero.go

58 lines
926 B
Go
Raw Normal View History

package main
const (
DIRECT = 1
REVERSE = 0
)
type Edge struct {
neighbor int
edgeType int
}
func minReorder(n int, connections [][]int) int {
var dfs func(int, int)
makeGraph := func() map[int]([]Edge) {
g := make(map[int]([]Edge))
for _, edge := range connections {
u, v := edge[0], edge[1]
neighbors, present := g[u]
if !present {
neighbors = make([]Edge, 0)
}
g[u] = append(neighbors, Edge{neighbor: v, edgeType: DIRECT})
neighbors, present = g[v]
if !present {
neighbors = make([]Edge, 0)
}
g[v] = append(neighbors, Edge{neighbor: u, edgeType: REVERSE})
}
return g
}
graph := makeGraph()
count := 0
dfs = func(parent, node int) {
neighbors, found := graph[node]
if !found {
return
}
for _, edge := range neighbors {
if edge.neighbor != parent {
count += edge.edgeType
dfs(node, edge.neighbor)
}
}
}
dfs(-1, 0)
return count
}