207.course-schedule.go 803 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Will visit, visiting, visited
  2. const (
  3. WILL = iota
  4. ING
  5. ED
  6. )
  7. func canFinish(numCourses int, prerequisites [][]int) bool {
  8. adj := make([][]bool, numCourses)
  9. for i := range adj {
  10. adj[i] = make([]bool, numCourses)
  11. }
  12. for i := range prerequisites {
  13. adj[prerequisites[i][0]][prerequisites[i][1]] = true
  14. }
  15. tag := make([]int, numCourses)
  16. hasRing := false
  17. for i := 0; i < numCourses; i++ {
  18. dfs(i, adj, &tag, &hasRing)
  19. if hasRing {
  20. return false
  21. }
  22. }
  23. return true
  24. }
  25. func dfs(x int, adj [][]bool, tag *[]int, hasRing *bool) {
  26. if *hasRing || (*tag)[x] == ED {
  27. return
  28. }
  29. (*tag)[x] = ING
  30. for i := range adj[x] {
  31. if !adj[x][i] {
  32. continue
  33. }
  34. if (*tag)[i] == WILL {
  35. dfs(i, adj, tag, hasRing)
  36. } else if (*tag)[i] == ING {
  37. *hasRing = true
  38. return
  39. }
  40. }
  41. (*tag)[x] = ED
  42. }