Note: study again. BFS cycle detection based on topological sorting (Kahn’s algorithm). If we don't visit every vertex in the topological sort, then we've ran into a cycle.
(numCourses int, prerequisites [][]int)
| 6 | // If we don't visit every vertex in the topological sort, then we've |
| 7 | // ran into a cycle. |
| 8 | func canFinishBFS(numCourses int, prerequisites [][]int) bool { |
| 9 | if len(prerequisites) == 0 { |
| 10 | return true |
| 11 | } |
| 12 | |
| 13 | adjList := make(map[int][]int) |
| 14 | for _, pre := range prerequisites { |
| 15 | adjList[pre[0]] = append(adjList[pre[0]], pre[1]) |
| 16 | } |
| 17 | |
| 18 | // calculate the in-degree for each vertex |
| 19 | inDegrees := make([]int, numCourses) |
| 20 | for _, prereq := range prerequisites { |
| 21 | inDegrees[prereq[1]]++ |
| 22 | } |
| 23 | |
| 24 | // enqueue all verticies with in-degree of 0 |
| 25 | zeroInQueue := make([]int, 0) |
| 26 | for course, inDegree := range inDegrees { |
| 27 | if inDegree == 0 { |
| 28 | zeroInQueue = append(zeroInQueue, course) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | return !hasCycleBFS(adjList, zeroInQueue, inDegrees, numCourses) |
| 33 | } |
| 34 | |
| 35 | func hasCycleBFS(adjList map[int][]int, zeroInQueue []int, |
| 36 | inDegrees []int, numVerticies int) bool { |