Commit 8856d3be authored by Roberts Ivanovs's avatar Roberts Ivanovs
Browse files

Added backtracking to the city_dikstra

parent 84d4ca10
......@@ -11,14 +11,17 @@ def mans_cels(city_1, city_2, matrix, cities):
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
visiting_curr = node_to_visit == curr_node or length >= 100
cannot_reach = length == inf
# Determine wether we're trying to access an invalid city
if visiting_curr or cannot_reach or node_visited:
# Calculate the new length to each of the connected city
if sum_dist[curr_node] + length < sum_dist[node_to_visit]:
sum_dist[node_to_visit] = sum_dist[curr_node] + length
......@@ -26,23 +29,38 @@ def mans_cels(city_1, city_2, matrix, cities):
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
# Find a connected node with the least distance
for i_node in range(0, len(cities)):
if not visited[i_node] and sum_dist[i_node] < curr_smallest_len:
curr_smallest_len = sum_dist[i_node]
curr_smallest_id = i_node
# If we're at the end node, trace back the graph
if visited[end_node]:
route = [cities[end_node]]
pos = end_node
while (pos != start_node):
for i_node in range(0, len(sum_dist)):
if i_node != pos and matrix[i_node][pos] != inf and sum_dist[pos] - \
matrix[i_node][pos] == sum_dist[i_node]:
pos = i_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)
matrix_data = generate_matrix()
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
"Ventspils", "Riga", matrix_data["matrix"], matrix_data["cities"]
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