一思路
拓扑排序,本质也可以理解成在图中找环,
入度或者出度的记录里迭代
二代码
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
from collections import defaultdict
graph = defaultdict(list)
visited = set()
for x, y in prerequisites:
graph[y].append(x)
def dfs(i, being_visited):
if i in being_visited: return False
if i in visited: return True
visited.add(i)
being_visited.add(i)
for j in graph[i]:
if not dfs(j, being_visited): return False
being_visited.remove(i)
return True
for i in range(numCourses):
if i in visited: continue
if not dfs(i, set()): return False
return True