LeetCode/go/all-ancestors-of-a-node-in-a-directed-acyclic-graph.go

35 lines
668 B
Go
Raw Normal View History

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
}