-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdijkstra.py
104 lines (80 loc) · 2.67 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
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
# -*- coding: utf-8 -*-
# Author: Cristian Bastidas
# GitHub: https://github.com/crixodia
# Date: 2020-10-7
from math import inf
wmat = [[0, 2, 0, 0, 0, 1, 0, 0],
[2, 0, 2, 2, 4, 0, 0, 0],
[0, 2, 0, 0, 3, 0, 0, 1],
[0, 2, 0, 0, 4, 3, 0, 0],
[0, 4, 3, 4, 0, 0, 7, 0],
[1, 0, 0, 3, 0, 0, 5, 0],
[0, 0, 0, 0, 7, 5, 0, 6],
[0, 0, 1, 0, 0, 0, 6, 0]]
def find_all(wmat, start, end=-1):
"""
Returns a tuple with a distances' list and paths' list of
all remaining vertices with the same indexing.
(distances, paths)
For example, distances[x] are the shortest distances from x
vertex which shortest path is paths[x]. x is an element of
{0, 1, ..., n-1} where n is the number of vertices
Args:
wmat -- weighted graph's adjacency matrix
start -- paths' first vertex
end -- (optional) path's end vertex. Return just the
distance and its path
Exceptions:
Index out of range, Be careful with start and end vertices
"""
n = len(wmat)
dist = [inf]*n
dist[start] = wmat[start][start] # 0
spVertex = [False]*n
parent = [-1]*n
path = [{}]*n
for count in range(n-1):
minix = inf
u = 0
for v in range(len(spVertex)):
if spVertex[v] == False and dist[v] <= minix:
minix = dist[v]
u = v
spVertex[u] = True
for v in range(n):
if not(spVertex[v]) and wmat[u][v] != 0 and dist[u] + wmat[u][v] < dist[v]:
parent[v] = u
dist[v] = dist[u] + wmat[u][v]
for i in range(n):
j = i
s = []
while parent[j] != -1:
s.append(j)
j = parent[j]
s.append(start)
path[i] = s[::-1]
return (dist[end], path[end]) if end >= 0 else (dist, path)
def find_shortest_path(wmat, start, end=-1):
"""
Returns paths' list of all remaining vertices.
Args:
wmat -- weigthted graph's adjacency matrix
start -- paths' first vertex
end -- (optional) path's end vertex. Return just
the path
Exceptions:
Index out of range, Be careful with start and end vertices.
"""
return find_all(wmat, start, end)[1]
def find_shortest_distance(wmat, start, end=-1):
"""
Returns distances' list of all remaining vertices.
Args:
wmat -- weigthted graph's adjacency matrix
start -- paths' first vertex
end -- (optional) path's end vertex. Return just
the distance
Exceptions:
Index out of range, Be careful with start and end vertices.
"""
return find_all(wmat, start, end)[0]