-
Notifications
You must be signed in to change notification settings - Fork 0
/
Uniform_Cost_Search.py
51 lines (40 loc) · 1.39 KB
/
Uniform_Cost_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
''' Considering the Map that is there in README to solve the Uniform Cost Search '''
import queue as Q
def search(graph, start, end):
if start not in graph:
raise TypeError(str(start) + ' not found in graph !')
return
if end not in graph:
raise TypeError(str(end) + ' not found in graph !')
return
queue = Q.PriorityQueue()
queue.put((0, [start]))
while not queue.empty():
node = queue.get()
current = node[1][len(node[1]) - 1]
if end in node[1]:
print("Path found: " + str(node[1]) + ", Cost = " + str(node[0]))
break
cost = node[0]
for neighbor in graph[current]:
temp = node[1][:]
temp.append(neighbor)
queue.put((cost + graph[current][neighbor], temp))
def read_Graph():
lines = int( input() )
graph = {}
for line in range(lines):
line = input()
tokens = line.split()
node = tokens[0]
graph[node] = {}
for i in range(1, len(tokens) - 1, 2):
# print(node, tokens[i], tokens[i + 1])
# graph.addEdge(node, tokens[i], int(tokens[i + 1]))
graph[node][tokens[i]] = int(tokens[i + 1])
return graph
def main():
graph = read_Graph()
search(graph, 'Arad', 'Bucharest')
if __name__ == "__main__":
main()