go: add «1466. Reorder Routes to Make All Paths Lead to the City Zero»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-12 12:46:02 +02:00
parent 28379bfe10
commit 8c0c14f406
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,57 @@
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
}