-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4-1.py
More file actions
32 lines (24 loc) · 646 Bytes
/
4-1.py
File metadata and controls
32 lines (24 loc) · 646 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
31
32
# Write an algorithm to determine if there is a path between two nodes in a directed graph
from queue import SimpleQueue
class Node:
def __init__(self, data):
self.data = data
self.neighbors = []
node = Node(1)
node2 = Node(2)
node2.neighbors = [Node(3)]
node.neighbors = [node2]
print(node.data)
print([n.data for n in node.neighbors])
def bfs(node, target):
q = SimpleQueue()
q.put(node)
while not q.empty():
n = q.get()
if n.data == target:
return True
for neighbor in n.neighbors:
q.put(neighbor)
return False
print(bfs(node, 3))
print(bfs(node, 9))