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:
parent
c56b3d121b
commit
92c5bae5aa
1 changed files with 34 additions and 0 deletions
34
go/all-ancestors-of-a-node-in-a-directed-acyclic-graph.go
Normal file
34
go/all-ancestors-of-a-node-in-a-directed-acyclic-graph.go
Normal 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
|
||||
}
|
Loading…
Reference in a new issue