generated from hexlet-boilerplates/python-package
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra.py
67 lines (50 loc) · 2.58 KB
/
dijkstra.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
# -*- coding:utf-8 -*-
"""Implementation Dijkstra’s algorithm."""
from graph_algorithms.data_structure.priority_queue.priority_queue import make_priority_queue
from graph_algorithms.data_structure.priority_queue.priority_queue import extract_min
from graph_algorithms.data_structure.priority_queue.priority_queue import set_priority
from graph_algorithms.data_structure.priority_queue.priority_queue import decrease_priority
from graph_algorithms.data_structure.priority_queue.priority_queue import is_empty
from graph_algorithms.data_structure.distance import make_distances
from graph_algorithms.data_structure.distance import set_distance
from graph_algorithms.algorithms.relax import relax
from graph_algorithms.algorithms.relax import edge_weight
from graph_algorithms.exception.graph_exception import NotContainsElementException
from graph_algorithms.exception.messages import not_contains_vertex_message
from graph_algorithms.exception.graph_exception import DataStructureIsEmptyException
from graph_algorithms.exception.messages import data_structure_is_empty_message
def dijkstra(graph, start_vertex):
"""Return the distance from the starting vertex to the rest.
Args:
graph: graph for search
start_vertex: start vertex for search
Raises:
DataStructureIsEmptyException: if graph is empty
NotContainsElementException: if graph not contains start vertex
Returns:
distances: collection storing the distance from the starting vertex to the rest
"""
if graph.is_empty:
raise DataStructureIsEmptyException(data_structure_is_empty_message())
if start_vertex.identifier not in graph:
raise NotContainsElementException(not_contains_vertex_message(start_vertex.identifier))
return _dijkstra(graph, start_vertex)
def _dijkstra(graph, start_vertex):
"""Return the distance from the starting vertex to the rest.
Args:
graph: graph for search
start_vertex: start vertex for search
Returns:
distances: collection storing the distance from the starting vertex to the rest
"""
distance = make_distances(graph)
priority_queue = make_priority_queue(graph)
set_distance(start_vertex, 0, distance)
set_priority(start_vertex, 0, priority_queue)
while not is_empty(priority_queue):
vertex = extract_min(priority_queue)
for adjacent_vertex in vertex:
if relax(vertex, adjacent_vertex, distance):
weight = edge_weight(vertex, adjacent_vertex, distance)
decrease_priority(adjacent_vertex, weight, priority_queue)
return distance