forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Accepted submission: _https://leetcode.com/submissions/detail/871343208/_
- Loading branch information
1 parent
4efac3d
commit 05441d3
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |