Skip to content

Commit baacc32

Browse files
authored
Create course-schedule-iv.py
1 parent 9258ad7 commit baacc32

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Python/course-schedule-iv.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Time: O(n^3)
2+
# Space: O(n^2)
3+
4+
class Solution(object):
5+
def checkIfPrerequisite(self, n, prerequisites, queries):
6+
"""
7+
:type n: int
8+
:type prerequisites: List[List[int]]
9+
:type queries: List[List[int]]
10+
:rtype: List[bool]
11+
"""
12+
def floydWarshall(n, graph):
13+
reachable = set(map(lambda x: x[0]*n+x[1], graph))
14+
for k in xrange(n):
15+
for i in xrange(n):
16+
for j in xrange(n):
17+
if i*n+j not in reachable and (i*n+k in reachable and k*n+j in reachable):
18+
reachable.add(i*n+j)
19+
return reachable
20+
21+
reachable = floydWarshall(n, prerequisites)
22+
return [i*n+j in reachable for i, j in queries]
23+
24+
25+
# Time: O(n * q)
26+
# Space: O(p + n)
27+
import collections
28+
29+
30+
class Solution2(object):
31+
def checkIfPrerequisite(self, n, prerequisites, queries):
32+
"""
33+
:type n: int
34+
:type prerequisites: List[List[int]]
35+
:type queries: List[List[int]]
36+
:rtyp
37+
"""
38+
graph = collections.defaultdict(list)
39+
for u, v in prerequisites:
40+
graph[u].append(v)
41+
result = []
42+
for i, j in queries:
43+
stk, lookup = [i], set([i])
44+
while stk:
45+
node = stk.pop()
46+
for nei in graph[node]:
47+
if nei in lookup:
48+
continue
49+
stk.append(nei)
50+
lookup.add(nei)
51+
result.append(j in lookup)
52+
return result

0 commit comments

Comments
 (0)