Skip to content

Instantly share code, notes, and snippets.

@alldroll
Last active March 4, 2020 15:33
Show Gist options
  • Select an option

  • Save alldroll/14f43ac0b9357829ec669ccc2f4a2bff to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/14f43ac0b9357829ec669ccc2f4a2bff to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/course-schedule
const (
free = byte(0)
observed = byte(1)
visited = byte(2)
)
func canFinish(numCourses int, prerequisites [][]int) bool {
if len(prerequisites) == 0 {
return true
}
graph := make([][]int, numCourses)
states := make([]byte, numCourses)
for _, pair := range prerequisites {
from, to := pair[0], pair[1]
graph[from] = append(graph[from], to)
}
result := true
for i := 0; i < numCourses && result; i++ {
if isCycle(graph, i, states) {
result = false
}
}
return result
}
func isCycle(graph [][]int, from int, states []byte) bool {
if len(graph[from]) == 0 || states[from] == visited {
return false
}
if states[from] == observed {
return true
}
states[from] = observed
for _, to := range graph[from] {
if from == to || isCycle(graph, to, states) {
return true
}
}
states[from] = visited
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment