-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcourseScheduleII.py
More file actions
55 lines (51 loc) · 1.64 KB
/
courseScheduleII.py
File metadata and controls
55 lines (51 loc) · 1.64 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/course-schedule-ii/
# Author: Miao Zhang
# Date: 2021-01-26
# dfs
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
from collections import defaultdict
graph = defaultdict(list)
for u, v in prerequisites:
graph[u].append(v)
visited = [0] * numCourses
path = []
for i in range(numCourses):
if not self.dfs(graph, visited, i, path):
return []
return path
def dfs(self, graph, visited, i, path):
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, path):
return False
visited[i] = 2
path.append(i)
return True
# bfs
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
from collections import defaultdict
graph = defaultdict(list)
indegrees = defaultdict(int)
for u, v in prerequisites:
graph[v].append(u)
indegrees[u] += 1
path = []
for i in range(numCourses):
zeroDegree = False
for j in range(numCourses):
if indegrees[j] == 0:
zeroDegree = True
break
if not zeroDegree:
return []
indegrees[j] -= 1
for node in graph[j]:
indegrees[node] -= 1
path.append(j)
return path