-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourseSchedule.py
More file actions
54 lines (46 loc) · 1.35 KB
/
Copy pathCourseSchedule.py
File metadata and controls
54 lines (46 loc) · 1.35 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
# preq = [[0, 1], [0, 2], [1, 3], [1, 4], [3, 4]]
preq = [[0, 1], [1, 0]]
visited = []
parent = {}
def canFinish(edges, num): # num = number of course
pre = {i: [] for i in range(num)}
for c, p in edges:
pre[c].append(p)
print(pre)
r = dfs(pre)
return r
def dfs(pre):
for crs, adj_pre in pre.items():
print('parent: ', parent)
print('visited: ', visited)
if crs not in visited:
visited.append(crs)
if crs not in parent:
parent[crs] = None
if not adj_pre == []:
for item in adj_pre:
print('preq: ', item)
res = dfs_depth(pre, item)
print('res: ', res)
if res == False:
return False
if res == True:
pre[crs].remove(item)
return tuple(True, visited[::-1])
def dfs_depth(pre, i):
global parent
if not pre[i]:
visited.append(i)
return True
else:
for v in pre[i]:
if v not in parent:
print('v: ', v)
elif v in visited:
if v in parent:
return False
if v not in visited:
visited.append(i)
dfs_depth(pre, v)
return True
print(canFinish(preq, 5))