-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhasPath.py
More file actions
65 lines (51 loc) · 1.49 KB
/
Copy pathhasPath.py
File metadata and controls
65 lines (51 loc) · 1.49 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
56
57
58
59
60
61
62
63
64
65
'''
Write a function, has_path, that takes in a dictionary representing the adjacency list of a directed acyclic graph and two nodes (src, dst).
The function should return a boolean indicating whether or not there exists a directed path between the source and destination nodes.
'''
# depth-first
def has_path(graph, src, dst):
'''
Time: O(edges)
Space: O(nodes)
'''
if src == dst: return True
for neighbor in graph[src]:
if has_path(graph, neighbor, dst):
return True
return False
# breadth-first
def has_path_bfs(graph, src, dst):
'''
Time: O(edges)
Space: O(nodes)
'''
queue = [src]
while queue:
current = queue.pop(0)
if current == dst:
return True
for neighbor in graph[current]:
queue.append(neighbor)
return False
def main():
# Test graph
graph = {
'f': ['g', 'i'],
'g': ['h'],
'h': [],
'i': ['g', 'k'],
'j': ['i'],
'k': []
}
assert has_path(graph, 'f', 'k') == True
assert has_path_bfs(graph, 'f', 'k') == True
print("Test case 1 - passed")
assert has_path(graph, 'f', 'j') == False
assert has_path_bfs(graph, 'f', 'j') == False
print("Test case 2 - passed")
assert has_path(graph, 'i', 'h') == True
assert has_path_bfs(graph, 'i', 'h') == True
print("Test case 3 - passed")
print ("All test cases passed!!")
if __name__ == '__main__':
main()