Commit f14dcb59 authored by Roberts Ivanovs's avatar Roberts Ivanovs
Browse files

Created a dijkstra algorithm for traversing cities

parent 3f67cfd9
from math import inf
from data_validation import generate_matrix
def mans_cels(city_1, city_2, matrix, cities):
start_node = cities.index(city_1)
end_node = cities.index(city_2)
sum_dist = [inf] * len(cities)
sum_dist[start_node] = 0
curr_node = start_node
visited = [False] * len(cities)
for iteration in range(0, len(cities)):
# for iteration in range(0, len(sum_dist)):
for node_to_visit in range(0, len(sum_dist)):
length = matrix[curr_node][node_to_visit]
node_visited = visited[node_to_visit]
visiting_curr = node_to_visit == curr_node
cannot_reach = length == inf
if visiting_curr or cannot_reach or node_visited:
if sum_dist[curr_node] + length < sum_dist[node_to_visit]:
sum_dist[node_to_visit] = sum_dist[curr_node] + length
visited[curr_node] = True
curr_smallest_len = inf
curr_smallest_id = 0
for iter_node in range(0, len(cities)):
if not visited[iter_node
] and sum_dist[iter_node] < curr_smallest_len:
curr_smallest_len = sum_dist[iter_node]
curr_smallest_id = iter_node
city_to_visit = cities[curr_smallest_id]
print(f"Next city to visit {city_to_visit}")
curr_node = curr_smallest_id
if visited[end_node]:
print("sum_dist", sum_dist)
print("visited", visited)
if __name__ == "__main__":
matrix_data = generate_matrix(50)
cities_string = ", ".join(matrix_data['cities'])
print(f"Availaible cities {cities_string}")
mans_cels("Balvi", "Aluksne", matrix_data["matrix"], matrix_data["cities"])
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment