Skip to content

Instantly share code, notes, and snippets.

@HauptJ
Created February 12, 2020 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HauptJ/3c953043b04a944d74eebebdbf71ea0f to your computer and use it in GitHub Desktop.
Save HauptJ/3c953043b04a944d74eebebdbf71ea0f to your computer and use it in GitHub Desktop.
from collections import defaultdict
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
gra = Graph(len(prerequisites))
for preReq in prerequisites:
gra.addEdge(preReq[0], preReq[1])
for j in range(1, gra.V):
if gra.dfsUtil(j) == False:
return False
return True
class Graph:
def __init__(self, verticies):
self.V = verticies + 1
self.graph = defaultdict(list)
self.time = 0
self.parent = [-1] * self.V
self.low = [float("Inf")] * self.V
self.disc = [float("Inf")] * self.V
self.visited = [False] * self.V
def addEdge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def dfsUtil(self, u):
self.visited[u] = True
self.low[u] = self.time
self.disc[u] = self.time
self.time += 1
for v in self.graph[u]:
if self.visited[v] == True:
return False
if self.visited[v] == False:
self.parent[v] = u
self.dfsUtil(v)
self.low[u] = min(self.low[u], self.low[v])
elif v != self.parent[u]:
self.low[u] = min(self.low[u], self.disc[v])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment