-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphDFSandBFS.py
More file actions
73 lines (57 loc) · 1.66 KB
/
graphDFSandBFS.py
File metadata and controls
73 lines (57 loc) · 1.66 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
66
67
68
69
70
71
72
73
# creating an adjacency list
from collections import deque
airports = 'PHX BKK OKC JFK LAX MEX EZE HEL LOS LAP LIM'.split(' ')
routes = [
['PHX', 'LAX'],
['PHX', 'JFK'],
['JFK', 'OKC'],
['JFK', 'HEL'],
['JFK', 'LOS'],
['MEX', 'LAX'],
['MEX', 'BKK'],
['MEX', 'LIM'],
['MEX', 'EZE'],
['LIM', 'BKK']
]
adjacencyList = {}
def addEdge(origin, destination):
adjacencyList[origin].append(destination)
adjacencyList[destination].append(origin)
#create graph
for airport in airports:
adjacencyList[airport] = []
for route in routes:
addEdge(route[0], route[1])
print(adjacencyList)
#BFS - iterative
#queue, initally has root, remove each element and add it's children if they exist,
#keep going until queue is empty
def bfs(start):
queue = deque(start)
visted = set()
while(len(queue) > 0):
print(queue)
airport = queue.popleft()
destinations = adjacencyList[airport]
for destination in destinations:
print(destination)
if destination == "BKK":
print("found it")
if destination not in visted:
visted.add(destination)
queue.append(destination)
#dfs - recursive
#go deep into each node, then backtrack and follow same pattern
def dfs(start, setty):
if start in setty:
return
setty.add(start)
destinations = adjacencyList[start]
for destination in destinations:
if destination == "BKK":
print("found it")
if destination not in setty:
dfs(destination, setty)
empset = set()
dfs("PHX", empset)
# bfs(["PHX"])