algorithm project (1)
algorithm project (1)
276km
A
E
141km
164km
B 134km
72km
D
226km
C
KEY:
A HARARE
B KADOMA
C KWEKWE
D GWERU
E BULAWAYO
A D 275 KM
A B 141 KM
B C 72 KM
C D 134 KM
C E 226 KM
D E 164 KM
2. Use a programming language of your choice to implement the Graph in (1) above.
The Graph system should be able to suggest the shortest path a traveler could take
between any cities. Make sure your code is well documented with comments, blank
lines, indentions and necessary explanations.
[30]
Code in python:
How Dijkstra Algorithm works:
In the diagram, cities are represented by nodes and the edges
reflect the roads (/paths) that can be taken. The source node
which is the start in the code shown above is Harare. Destination
node which is the goal is Masvingo, however, it can be any of the
other nodes. Source node is assigned 0 because it’s the start thus
no distance has been travelled. All other nodes are assigned
infinity because initially we don’t know if there are any paths to
get to the various nodes. As the possible paths are found to other
nodes the code is modified. After the path is found then distance
is recorded instead of infinity for example before travelling to
Gweru via Harare it was infinity after the node is explored the
distance infinity changes to 275km. As soon as a node is visited it
will be marked as visited, Dijkstra’s algorithm doesn’t allow
backtracking, each node can only be visited once. When selecting
the shortest distance, it picks the smallest edge of the vertex that
has not been chosen yet as it can’t backtrack. This algorithm
works by creating a queue of distance values and looking through
the edges of each node.it repeats a two-part process of updating
estimates and choosing the next vertex which is the unexpected
city/node with the smallest estimate. Each of the visited nodes
have their distances that are added together and compared and
the smaller value is taken.