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:
parent
28379bfe10
commit
8c0c14f406
1 changed files with 57 additions and 0 deletions
57
go/reorder-routes-to-make-all-paths-lead-to-the-city-zero.go
Normal file
57
go/reorder-routes-to-make-all-paths-lead-to-the-city-zero.go
Normal 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
|
||||||
|
}
|
Loading…
Reference in a new issue