-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcourseSchedule.py
More file actions
31 lines (27 loc) · 878 Bytes
/
courseSchedule.py
File metadata and controls
31 lines (27 loc) · 878 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/course-schedule/
# Author: Miao Zhang
# Date: 2021-01-26
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
from collections import defaultdict
graph = defaultdict(list)
for u, v in prerequisites:
graph[u].append(v)
visited = [0] * numCourses
for i in range(numCourses):
if not self.dfs(graph, visited, i):
return False
return True
def dfs(self, graph, visited, i):
if visited[i] == 1:
return False
if visited[i] == 2:
return True
visited[i] = 1
for j in graph[i]:
if not self.dfs(graph, visited, j):
return False
visited[i] = 2
return True