Skip to content

Commit

Permalink
Create 0210-course-schedule-ii.go
Browse files Browse the repository at this point in the history
  • Loading branch information
AP-Repositories authored Jan 4, 2023
1 parent 4efac3d commit 05441d3
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions go/0210-course-schedule-ii.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const CRS = 0
const PRE = 1
func findOrder(numCourses int, prerequisites [][]int) []int {
prereq := make([][]int, 0)
for i := 0; i < numCourses; i++ {
prereq = append(prereq, make([]int, 0))
}
for _, edge := range prerequisites {
prereq[edge[CRS]] = append(prereq[edge[CRS]], edge[PRE])
}

output := make([]int, 0)
visit, cycle := make([]bool, numCourses), make([]bool, numCourses)

var dfs func(int) bool
dfs = func(crs int) bool {
if cycle[crs] {
return false
} else if visit[crs] {
return true
}

cycle[crs] = true
for _, pre := range prereq[crs] {
if !dfs(pre) {
return false
}
}
cycle[crs] = false
visit[crs] = true
output = append(output, crs)
return true
}

for c := 0; c < numCourses; c++ {
if dfs(c) == false {
return []int{}
}
}
return output
}

0 comments on commit 05441d3

Please sign in to comment.