-
Notifications
You must be signed in to change notification settings - Fork 32
/
bfs.py
65 lines (52 loc) · 1.32 KB
/
bfs.py
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
import collections
class Queue:
def __init__(self):
self.elements = collections.deque()
def empty(self):
return len(self.elements) == 0
def put(self, x):
self.elements.append(x)
def get(self):
return self.elements.popleft()
class SimpleGraph:
def __init__(self):
self.edges = {}
def neighbors(self, id):
return self.edges[id]
class Graph:
def __init__(self):
self.graph=[]
def neighbors(self,id):
return self.graph[id]
def breadth_first_search_1(graph, start):
# print out what we find
frontier = Queue()
frontier.put(start)
visited = {}
visited[start] = True
while not frontier.empty():
current = frontier.get()
print("Visiting %r" % current)
neighbors=graph.neighbors(current)
for i in range(0,len(neighbors)):
next=neighbors[i]
if next==1:
if i not in visited:
frontier.put(i)
visited[i] = True
# example_graph = SimpleGraph()
# example_graph.edges = {
# '1': ['2'],
# '2': ['1', '3', '4'],
# '3': ['1'],
# '4': ['5', '1'],
# '5': ['2']
# }
Matgraph=Graph()
Matgraph.graph=[[0,1,0,0,0],
[1,0,1,1,0],
[1,0,0,0,0],
[1,0,0,0,1],
[0,1,0,0,0]]
#print (Matgraph.neighbors(1))
breadth_first_search_1(Matgraph,0)