MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / canFinishBFS

Function canFinishBFS

course_schedule_207/solution.go:8–33  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

6// If we don't visit every vertex in the topological sort, then we've
7// ran into a cycle.
8func 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
35func hasCycleBFS(adjList map[int][]int, zeroInQueue []int,
36 inDegrees []int, numVerticies int) bool {

Callers 1

Test_canFinishFunction · 0.85

Calls 1

hasCycleBFSFunction · 0.85

Tested by 1

Test_canFinishFunction · 0.68