mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 21:22:43 +00:00
feat(work): implement Course Schedule II solution
This commit is contained in:
1 parent
ca73d3235c
commit
0009075138
2 files changed
+64
No files matched your search
@@ -36,4 +36,36 @@ sidebar:
|
|||||||
```py
|
```py
|
||||||
class Solution:
|
class Solution:
|
||||||
def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]:
|
def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]:
|
||||||
|
prereq = {c: [] for c in range(numCourses)}
|
||||||
|
for crs, pre in prerequisites:
|
||||||
|
prereq[crs].append(pre)
|
||||||
|
|
||||||
|
# course has 3 possible states:
|
||||||
|
# visited -> crs has been added to output
|
||||||
|
# visiting -> crs not added to output, but added to cycle
|
||||||
|
# unvisited -> crs not added to output nor cycle
|
||||||
|
output = []
|
||||||
|
visit, cycle = set(), set()
|
||||||
|
|
||||||
|
def dfs(crs):
|
||||||
|
if crs in cycle:
|
||||||
|
return False
|
||||||
|
if crs in visit:
|
||||||
|
return True
|
||||||
|
|
||||||
|
cycle.add(crs)
|
||||||
|
for pre in prereq[crs]:
|
||||||
|
if dfs(pre) == False:
|
||||||
|
return False
|
||||||
|
|
||||||
|
cycle.remove(crs)
|
||||||
|
visit.add(crs)
|
||||||
|
output.append(crs)
|
||||||
|
return True
|
||||||
|
|
||||||
|
for c in range(numCourses):
|
||||||
|
if dfs(c) == False:
|
||||||
|
return []
|
||||||
|
|
||||||
|
return output
|
||||||
```
|
```
|
||||||
@@ -59,6 +59,38 @@ Constraints:
|
|||||||
• All the pairs [ai, bi] are distinct.
|
• All the pairs [ai, bi] are distinct.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
class Solution:
|
||||||
def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]:
|
def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]:
|
||||||
|
prereq = {c: [] for c in range(numCourses)}
|
||||||
|
for crs, pre in prerequisites:
|
||||||
|
prereq[crs].append(pre)
|
||||||
|
|
||||||
|
# course has 3 possible states:
|
||||||
|
# visited -> crs has been added to output
|
||||||
|
# visiting -> crs not added to output, but added to cycle
|
||||||
|
# unvisited -> crs not added to output nor cycle
|
||||||
|
output = []
|
||||||
|
visit, cycle = set(), set()
|
||||||
|
|
||||||
|
def dfs(crs):
|
||||||
|
if crs in cycle:
|
||||||
|
return False
|
||||||
|
if crs in visit:
|
||||||
|
return True
|
||||||
|
|
||||||
|
cycle.add(crs)
|
||||||
|
for pre in prereq[crs]:
|
||||||
|
if dfs(pre) == False:
|
||||||
|
return False
|
||||||
|
|
||||||
|
cycle.remove(crs)
|
||||||
|
visit.add(crs)
|
||||||
|
output.append(crs)
|
||||||
|
return True
|
||||||
|
|
||||||
|
for c in range(numCourses):
|
||||||
|
if dfs(c) == False:
|
||||||
|
return []
|
||||||
|
|
||||||
|
return output
|
||||||
Reference in new issue
Block a user