From 8c0c14f40678295172e88faea4a3359e0b432c24 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 12 Aug 2024 12:46:02 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1466.=20Reorder=20Routes=20to?= =?UTF-8?q?=20Make=20All=20Paths=20Lead=20to=20the=20City=20Zero=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...to-make-all-paths-lead-to-the-city-zero.go | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 go/reorder-routes-to-make-all-paths-lead-to-the-city-zero.go 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 +}