From 92c5bae5aa446ad727dfd0e94ec5044a30d1de00 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 29 Jun 2024 14:11:16 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB2192.=20All=20Ancestors=20of?= =?UTF-8?q?=20a=20Node=20in=20a=20Directed=20Acyclic=20Graph=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...s-of-a-node-in-a-directed-acyclic-graph.go | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 go/all-ancestors-of-a-node-in-a-directed-acyclic-graph.go diff --git a/go/all-ancestors-of-a-node-in-a-directed-acyclic-graph.go b/go/all-ancestors-of-a-node-in-a-directed-acyclic-graph.go new file mode 100644 index 0000000..708fbe8 --- /dev/null +++ b/go/all-ancestors-of-a-node-in-a-directed-acyclic-graph.go @@ -0,0 +1,34 @@ +package main + +func getAncestors(n int, edges [][]int) [][]int { + fromEdges := func() [][]int { + neighbours := make([][]int, n) + + for _, edge := range edges { + u, v := edge[0], edge[1] + neighbours[u] = append(neighbours[u], v) + } + + return neighbours + } + + neighbours := fromEdges() + ancestors := make([][]int, n) + + var dfs func(int, int) + dfs = func(ancestor, node int) { + for _, next := range neighbours[node] { + vertices := ancestors[next] + if len(vertices) == 0 || vertices[len(vertices)-1] != ancestor { + ancestors[next] = append(ancestors[next], ancestor) + dfs(ancestor, next) + } + } + } + + for i := range n { + dfs(i, i) + } + + return ancestors +}