Thursday, July 20, 2023

Dijkstra's algorithm with a graph

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:

  1. 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
  1. Create a set of visited vertices and initialize it to be empty.
Visited vertices = {}
  1. Add A to the visited vertices set.
Visited vertices = {A}
  1. 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)
  1. 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
  1. Repeat steps 4 and 5 for all unvisited neighbors of A.
Vertex | Distance from A
------- | --------
B | 2
C | 3
D | 4 (2 + 2)
  1. Remove A from the unvisited vertices set.
Visited vertices = {B, C}
  1. 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:

eLearning and Blackboard

  IT professional, U bring a unique set of skills and expertise that can greatly contribute to the successful development and implementati...