1136. Parallel Courses
找出是否有環
class Solution:
def minimumSemesters(self, n: int, relations: List[List[int]]) -> int:
if not relations:
return -1
table = defaultdict(list)
for prevCourse, nextCourse in relations:
table[prevCourse].append(nextCourse)
visited = {}
def hasCycle(currentCourse: int) -> bool:
if currentCourse in visited:
return visited[currentCourse]
visited[currentCourse] = True
for course in table[currentCourse]:
if backtrack(course):
return True
visited[currentCourse] = False
return visited[currentCourse]
for i in range(n):
if hasCycle(i):
return -1
# TODO合併
BFS
Last updated