-
Notifications
You must be signed in to change notification settings - Fork 0
/
greedy_search.py
71 lines (51 loc) · 1.83 KB
/
greedy_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
from cities import cities
class Node(object):
def __init__(self, name, parent):
self.name = name
self.parent = parent
self.f = 0
def __eq__(self, other):
return self.name == other.name
def __lt__(self, other):
return self.f < other.f
def __str__(self):
if self.parent:
return "Name: " + str(self.name) + " " + "Parent: " + self.parent.name + " Cost: " + str(self.f)
return "Name: " + str(self.name) + " " + "Parent: " + " None" + " Cost: " + str(self.f)
def check_opened(opened, new_node):
for node in opened:
if new_node == node and new_node.f >= node.f:
return False
return True
def greedy_search(start, finish):
opened = list()
closed = list()
graph = list()
start_node = Node(start, None)
finish_node = Node(finish, None)
opened.append(start_node)
while opened:
opened.sort()
current_node = opened.pop(0)
closed.append(current_node)
if current_node == finish_node:
path = list()
sum = 0
while current_node != start_node:
path.append(current_node)
if current_node:
sum += current_node.f
current_node = current_node.parent
return graph, path, sum
neighbors = list()
for neighbor in cities[current_node.name]:
neighbors.append(Node(neighbor["name"], current_node))
for next in neighbors:
for node in cities[current_node.name]:
if node["name"] == next.name:
next.f = node["dist"]
if next in closed:
continue
if check_opened(opened, next):
opened.append(next)
graph.append(current_node.name + " --> " + next.name)