Dijkstra's algorithm with a graph
A
/ \
B C
/ \ / \
D E F
The weight of each edge is shown next to the edge. The goal is to find the shortest path from A to all other vertices.
Here are the steps on how to apply Dijkstra's algorithm on this graph:
- Initialize the distance of all vertices to infinity except A, which is initialized to 0.
Vertex | Distance from A
------- | --------
A | 0
B | INF
C | INF
D | INF
E | INF
F | INF
- Create a set of visited vertices and initialize it to be empty.
Visited vertices = {}
- Add A to the visited vertices set.
Visited vertices = {A}
- For each unvisited neighbor of A, calculate the tentative distance to that neighbor as the distance to A plus the weight of the edge between A and that neighbor.
Vertex | Distance from A
------- | --------
B | 2 (0 + 2)
C | 3 (0 + 3)
- If the tentative distance is less than the current distance to that neighbor, update the current distance to that neighbor.
Vertex | Distance from A
------- | --------
B | 2
C | 3
- Repeat steps 4 and 5 for all unvisited neighbors of A.
Vertex | Distance from A
------- | --------
B | 2
C | 3
D | 4 (2 + 2)
- Remove A from the unvisited vertices set.
Visited vertices = {B, C}
- Repeat steps 3 to 7 until all vertices have been visited.
Vertex | Distance from A
------- | --------
B | 2
C | 3
D | 4
E | 5 (4 + 1)
F | 6 (4 + 2)
The shortest path from A to each vertex is as follows:
- A to B: A-B
- A to C: A-C
- A to D: A-B-D
- A to E: A-B-D-E
- A to F: A-B-D-F
No comments:
Post a Comment