123 lines
1.9 KiB
Python
Executable File
123 lines
1.9 KiB
Python
Executable File
graph = {
|
|
1: {
|
|
2: 7,
|
|
3: 9,
|
|
6: 14
|
|
},
|
|
2: {
|
|
1: 7,
|
|
3: 10,
|
|
4: 15
|
|
},
|
|
3: {
|
|
1: 9,
|
|
2: 10,
|
|
4: 11,
|
|
6: 2
|
|
},
|
|
4: {
|
|
2: 15,
|
|
3: 11,
|
|
5: 6,
|
|
},
|
|
5: {
|
|
4: 6,
|
|
6: 9,
|
|
},
|
|
6: {
|
|
1: 14,
|
|
5: 9,
|
|
3: 2
|
|
}
|
|
}
|
|
|
|
|
|
class GraphPoint:
|
|
def __init__(self, graph, number, routes):
|
|
self.graph = graph
|
|
self.number = number
|
|
self.routes = routes
|
|
self.visited = False
|
|
self.minimum_range = 9999
|
|
|
|
|
|
def get_unvisited_neighbours(self):
|
|
neighbours = []
|
|
for number in self.routes.keys():
|
|
point = self.graph.get_point(number)
|
|
if not point.visited:
|
|
neighbours.append(point)
|
|
return neighbours
|
|
|
|
|
|
def get_range(self, point):
|
|
return self.routes[point.number]
|
|
|
|
|
|
def get_all_neighbours(self):
|
|
neighbours = [self.graph.get_point(x) for x in self.routes.keys()]
|
|
return neighbours
|
|
|
|
|
|
|
|
class Graph:
|
|
def __init__(self, data):
|
|
self.data = data
|
|
self.points = {}
|
|
|
|
for number, routes in data.items():
|
|
self.points[number] = GraphPoint(self, number, routes)
|
|
|
|
self.points[1].minimum_range = 0
|
|
|
|
|
|
def get_point(self, number):
|
|
point = self.points.get(number)
|
|
|
|
if point is None:
|
|
raise ValueError(f"Graph has no point with number {number}")
|
|
|
|
return point
|
|
|
|
|
|
|
|
myGraph = Graph(graph)
|
|
|
|
|
|
start = myGraph.get_point(1)
|
|
queue = []
|
|
queue.append(start)
|
|
|
|
|
|
while len(queue) > 0:
|
|
current_point = min(queue, key=lambda x: x.minimum_range)
|
|
queue.remove(current_point)
|
|
current_point.visited = True
|
|
|
|
for neighbour in current_point.get_unvisited_neighbours():
|
|
new_range = current_point.minimum_range + current_point.get_range(neighbour)
|
|
|
|
if new_range < neighbour.minimum_range:
|
|
neighbour.minimum_range = new_range
|
|
|
|
queue.append(neighbour)
|
|
|
|
|
|
|
|
path = []
|
|
pos = myGraph.get_point(5)
|
|
|
|
|
|
while pos != start:
|
|
for neighbour in pos.get_all_neighbours():
|
|
if neighbour.get_range(pos) + neighbour.minimum_range == pos.minimum_range:
|
|
path.append(pos)
|
|
pos = neighbour
|
|
break
|
|
|
|
path.append(start)
|
|
|
|
for i in path[::-1]:
|
|
print(i.number)
|
|
# No comments here. Good l_ck!
|