mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
34 lines
668 B
Go
34 lines
668 B
Go
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
|
|
}
|