Advertisement
serega1112

207

Mar 6th, 2021
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.72 KB | None | 0 0
  1. class Solution:
  2.     def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
  3.        
  4.         g = defaultdict(list)
  5.         visited = defaultdict(int)
  6.        
  7.         for v in range(numCourses):
  8.             g[v] = []
  9.         for a, b in prerequisites:
  10.             g[b].append(a)
  11.            
  12.        
  13.         def dfs(v):
  14.             visited[v] = 1
  15.            
  16.             for n in g[v]:
  17.                 if visited[n] == 1 or (visited[n] == 0 and not dfs(n)):
  18.                     return False
  19.            
  20.             visited[v] = 2
  21.             return True
  22.        
  23.         for v in g:
  24.             if visited[v] == 0 and not dfs(v):
  25.                 return False
  26.            
  27.         return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement