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 +}