diff --git a/go/reorder-routes-to-make-all-paths-lead-to-the-city-zero.go b/go/reorder-routes-to-make-all-paths-lead-to-the-city-zero.go new file mode 100644 index 0000000..e43119d --- /dev/null +++ b/go/reorder-routes-to-make-all-paths-lead-to-the-city-zero.go @@ -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 +}