Created
April 14, 2020 04:27
-
-
Save pot-code/5a52c679ff91e736bd77e4118edbf1e1 to your computer and use it in GitHub Desktop.
[graph] graph algorithms #algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func topoTraverse(n int, edge [][]int) { | |
graph := make(map[int][]int) | |
inTable := make([]int, n) | |
for _, edge := range edge { | |
graph[edge[0]] = append(graph[edge[0]], edge[1]) | |
inTable[edge[1]]++ | |
} | |
var queue []int | |
for i, v := range inTable { | |
if v == 0 { | |
queue = append(queue, i) | |
} | |
} | |
for len(queue) > 0 { | |
for size := len(queue); size > 0; size-- { | |
n := queue[0] | |
queue = queue[1:] | |
for _, c := range graph[n] { | |
inTable[c]-- | |
if inTable[c] == 0 { | |
queue = append(queue, c) | |
} | |
} | |
delete(graph, n) | |
} | |
} | |
for _, v := range inTable { | |
if v > 0 { | |
panic("cycle") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment