forked from MirjanaBlazhevska/FEIT01L006
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.py
268 lines (247 loc) · 11 KB
/
search.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
from collections import deque
from graph import Graph, WeightedGraph
import heapq
def breadth_first_search_traversal(graph, starting_vertex, goal_vertex=None, verbose=False):
"""
Breadth first search algorithm
:param graph: graph dictionary to traverse
:param starting_vertex: vertext to start from
:param goal_vertex: vertex to look for
:param verbose: True for debug options
:return: None
"""
if starting_vertex == goal_vertex:
if verbose:
print('Почетниот и бараниот јазол се исти')
return
visited = {starting_vertex}
queue = deque([starting_vertex])
while queue:
if verbose:
print('Ред за разгранување:')
for element in queue:
print(element, end=' ')
print()
print()
vertex = queue.popleft()
if verbose:
print('Го разгрануваме јазолот {}'.format(vertex))
for neighbour in graph[vertex]:
if neighbour in visited:
if verbose:
print('{} е веќе посетен'.format(neighbour))
else:
if verbose:
print('{}, кој е соседен јазол на {} го немаме посетено до сега, затоа го додаваме во редот '
'за разгранување и го означуваме како посетен'.format(neighbour, vertex))
if neighbour == goal_vertex:
if verbose:
print('Го пронајдовме посакуваниот јазол', neighbour)
return
visited.add(neighbour)
queue.append(neighbour)
if verbose:
print()
def depth_first_search_traversal(graph, starting_vertex, goal_vertex=None, verbose=False):
"""
Depth first search algorithm
:param graph: graph dictionary to traverse
:param starting_vertex: vertext to start from
:param goal_vertex: vertex to look for
:param verbose: True for debug options
:return: None
"""
if starting_vertex == goal_vertex:
if verbose:
print('Почетниот и бараниот јазол се исти')
return
visited = {starting_vertex}
queue = deque([starting_vertex])
while queue:
if verbose:
print('Ред за разгранување:')
for element in queue:
print(element, end=' ')
print()
print()
vertex = queue.popleft()
if verbose:
print('Го разгрануваме јазолот {}'.format(vertex))
for neighbour in graph[vertex]:
if neighbour in visited:
if verbose:
print('{} е веќе посетен'.format(neighbour))
else:
if verbose:
print('{}, кој е соседен јазол на {} го немаме посетено до сега, затоа го додаваме во редот '
'за разгранување и го означуваме како посетен'.format(neighbour, vertex))
if neighbour == goal_vertex:
if verbose:
print('Го пронајдовме посакуваниот јазол', neighbour)
return
visited.add(neighbour)
queue.appendleft(neighbour)
if verbose:
print()
def breadth_first_search_find_path(graph, starting_vertex, goal_vertex, verbose=False):
"""
Breadth first search algorithm with recorded path from starting vertex to goal vertex
:param graph: graph dictionary to traverse
:param starting_vertex: vertext to start from
:param goal_vertex: vertex to look for
:param verbose: True for debug options
:returns: path from starting vertex to goal vertex
"""
if starting_vertex == goal_vertex:
if verbose:
print('Почетниот и бараниот јазол се исти')
return []
visited = {starting_vertex}
queue = deque([[starting_vertex]])
while queue:
if verbose:
print('Ред за разгранување:')
for element in queue:
print(element, end=' ')
print()
print()
vertex_list = queue.popleft()
vertex_to_expand = vertex_list[-1]
if verbose:
print('Го разгрануваме јазолот {}'.format(vertex_to_expand))
for neighbour in graph[vertex_to_expand]:
if neighbour in visited:
if verbose:
print('{} е веќе посетен'.format(neighbour))
else:
if verbose:
print('{}, кој е соседен јазол на {} го немаме посетено до сега, затоа го додаваме во редот '
'за разгранување и го означуваме како посетен'.format(neighbour, vertex_to_expand))
if neighbour == goal_vertex:
if verbose:
print('Го пронајдовме посакуваниот јазол {}. Патеката да стигнеме до тука е {}'
.format(neighbour, vertex_list + [neighbour]))
return vertex_list + [neighbour]
visited.add(neighbour)
queue.append(vertex_list + [neighbour])
if verbose:
print()
def depth_first_search_find_path(graph, starting_vertex, goal_vertex, verbose=False):
"""
Depth first search algorithm with recorded path from starting vertex to goal vertex
:param graph: graph dictionary to traverse
:param starting_vertex: vertext to start from
:param goal_vertex: vertex to look for
:param verbose: True for debug options
:returns: path from starting vertex to goal vertex
"""
if starting_vertex == goal_vertex:
if verbose:
print('Почетниот и бараниот јазол се исти')
return
visited = {starting_vertex}
queue = deque([[starting_vertex]])
while queue:
if verbose:
print('Ред за разгранување:')
for element in queue:
print(element, end=' ')
print()
print()
vertex_list = queue.popleft()
vertex_to_expand = vertex_list[-1]
if verbose:
print('Го разгрануваме јазолот {}'.format(vertex_to_expand))
for neighbour in graph[vertex_to_expand]:
if neighbour in visited:
if verbose:
print('{} е веќе посетен'.format(neighbour))
else:
if verbose:
print('{}, кој е соседен јазол на {} го немаме посетено до сега, затоа го додаваме во редот '
'за разгранување и го означуваме како посетен'.format(neighbour, vertex_to_expand))
if neighbour == goal_vertex:
if verbose:
print('Го пронајдовме посакуваниот јазол {}. Патеката да стигнеме до тука е {}'
.format(neighbour, vertex_list + [neighbour]))
return vertex_list + [neighbour]
visited.add(neighbour)
queue.appendleft(vertex_list + [neighbour])
if verbose:
print()
def djikstra(graph, starting_vertex, goal_vertex, verbose=False):
"""
Djikstra's algorithm
:param graph: graph dictionary to traverse
:param starting_vertex: vertext to start from
:param goal_vertex: vertex to look for
:param verbose: True for debug options
:returns: optimal path from starting vertex to goal vertex
"""
if starting_vertex == goal_vertex:
if verbose:
print('Почетниот и бараниот јазол се исти')
return
expanded = set()
queue = [(0, [starting_vertex])]
heapq.heapify(queue)
while queue:
if verbose:
print('Ред за разгранување:')
for element in queue:
print(element, end=' ')
print()
print()
weight, vertex_list = heapq.heappop(queue)
vertex_to_expand = vertex_list[-1]
if vertex_to_expand == goal_vertex:
if verbose:
print('Го пронајдовме посакуваниот јазол {}. Патеката да стигнеме до тука е {} со цена {}'
.format(vertex_to_expand, vertex_list, weight))
return weight, vertex_list
if vertex_to_expand in expanded:
if verbose:
print('{} е веќе разгранет'.format(vertex_to_expand, weight, vertex_list))
continue
if verbose:
print('Го разгрануваме јазолот {} од ({}, {})'.format(vertex_to_expand, weight, vertex_list))
for neighbour, new_weight in graph[vertex_to_expand].items():
if neighbour in expanded:
if verbose:
print('{} е веќе разгранет'.format(neighbour))
else:
if verbose:
print('{} со тежина {}, кој е соседен јазол на {}, го додаваме во редот за разгранување со нова '
'цена и го означуваме како разгранет'.format(neighbour, new_weight, vertex_to_expand))
heapq.heappush(queue, (weight + new_weight, vertex_list + [neighbour]))
expanded.add(vertex_to_expand)
if verbose:
print()
if __name__ == '__main__':
g = Graph()
g.add_edge(('A', 'B'))
g.add_edge(('B', 'C'))
g.add_edge(('C', 'D'))
g.add_edge(('D', 'E'))
g.add_edge(('E', 'F'))
g.add_edge(('F', 'G'))
g.add_edge(('G', 'H'))
g.add_edge(('H', 'I'))
g.add_edge(('I', 'J'))
g.add_edge(('J', 'A'))
g.add_edge(('C', 'H'))
depth_first_search_traversal(graph=g.graph_dict, starting_vertex='A', goal_vertex='F', verbose=True)
path = breadth_first_search_find_path(graph=g.graph_dict, starting_vertex='A', goal_vertex='F', verbose=True)
print(path)
wg = WeightedGraph()
wg.add_edge(('A', 'B'), 7)
wg.add_edge(('B', 'C'), 10)
wg.add_edge(('A', 'C'), 9)
wg.add_edge(('B', 'D'), 15)
wg.add_edge(('C', 'D'), 11)
wg.add_edge(('A', 'E'), 14)
wg.add_edge(('C', 'E'), 2)
wg.add_edge(('E', 'F'), 9)
wg.add_edge(('F', 'D'), 6)
cost, path = djikstra(wg.graph_dict, 'A', 'F', True)
print(cost, path)