Created
February 12, 2020 03:20
-
-
Save HauptJ/3c953043b04a944d74eebebdbf71ea0f to your computer and use it in GitHub Desktop.
207. Course Schedule - https://leetcode.com/problems/course-schedule/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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