1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

go: add «2192. All Ancestors of a Node in a Directed Acyclic Graph»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-06-29 14:11:16 +02:00
parent c56b3d121b
commit 92c5bae5aa
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

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