ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Fortran Dijkstra's Algorithm for Shortest Path

Fortran

Goal -- WPM

Ready
Exercise Algorithm Area
1PROGRAM dijkstra_example
2IMPLICIT NONE
3
4INTEGER, PARAMETER :: MAX_NODES = 10
5INTEGER, PARAMETER :: INF = HUGE(0)
6INTEGER :: graph(MAX_NODES, MAX_NODES)
7INTEGER :: dist(MAX_NODES)
8LOGICAL :: visited(MAX_NODES)
9INTEGER :: num_nodes, source_node
10INTEGER :: i, j, u, v
11
12! Example graph (adjacency matrix)
13! 0 means no direct edge
14num_nodes = 5
15graph = RESHAPE([0, 4, 0, 0, 0,
164, 0, 8, 0, 0,
170, 8, 0, 7, 0,
180, 0, 7, 0, 9,
190, 0, 0, 9, 0], SHAPE(graph))
20
21source_node = 1
22
23PRINT *, "Graph represented by adjacency matrix:"
24DO i = 1, num_nodes
25PRINT *, graph(i, :)
26END DO
27PRINT *
28
29CALL dijkstra(graph, dist, visited, num_nodes, source_node)
30
31PRINT *, "Shortest distances from source node ", source_node, ":"
32DO i = 1, num_nodes
33IF (dist(i) == INF) THEN
34PRINT *, "Node ", i, ": INF"
35ELSE
36PRINT *, "Node ", i, ": ", dist(i)
37END IF
38END DO
39
40CONTAINS
41
42SUBROUTINE dijkstra(graph, dist, visited, num_nodes, source_node)
43IMPLICIT NONE
44INTEGER, INTENT(IN) :: graph(num_nodes, num_nodes)
45INTEGER, INTENT(OUT) :: dist(num_nodes)
46LOGICAL, INTENT(OUT) :: visited(num_nodes)
47INTEGER, INTENT(IN) :: num_nodes, source_node
48INTEGER :: i, u, v
49INTEGER :: min_dist, min_index
50
51! Initialize distances and visited status
52dist = INF
53visited = .FALSE.
54dist(source_node) = 0
55
56! Main loop: find shortest path for all nodes
57DO i = 1, num_nodes - 1
58! Pick the minimum distance vertex from the set of vertices not yet processed.
59! u is always equal to source_node in the first iteration.
60min_dist = INF
61min_index = -1
62
63DO v = 1, num_nodes
64IF (.NOT. visited(v) .AND. dist(v) <= min_dist) THEN
65min_dist = dist(v)
66min_index = v
67END IF
68END DO
69
70u = min_index
71IF (u == -1) EXIT ! Graph might be disconnected
72
73visited(u) = .TRUE.
74
75! Update dist value of the adjacent vertices of the picked vertex.
76DO v = 1, num_nodes
77! Update dist(v) only if it is not in visited, there is an edge from u to v,
78! and total weight of path from source to v through u is smaller than current value of dist(v)
79IF (.NOT. visited(v) .AND. graph(u, v) /= 0 .AND. &
80dist(u) /= INF .AND. dist(u) + graph(u, v) < dist(v)) THEN
81dist(v) = dist(u) + graph(u, v)
82END IF
83END DO
84END DO
85
86! Mark the last node as visited if it was reachable
87! This handles cases where the last node processed might be the only one left
88IF (min_index /= -1) visited(min_index) = .TRUE.
89
90END SUBROUTINE dijkstra
91
92END PROGRAM dijkstra_example
Algorithm description viewbox

Fortran Dijkstra's Algorithm for Shortest Path

Algorithm description:

This Fortran program implements Dijkstra's algorithm to find the shortest paths from a single source node to all other nodes in a graph with non-negative edge weights. It uses an adjacency matrix to represent the graph and iteratively selects the unvisited node with the smallest known distance from the source, updating the distances of its neighbors. This algorithm is fundamental in network routing protocols, GPS navigation systems, and finding the fastest routes in various applications.

Algorithm explanation:

Dijkstra's algorithm has a time complexity of O(V^2) when using an adjacency matrix and a simple linear scan to find the minimum distance vertex, or O(E + V log V) with a binary heap priority queue. The space complexity is O(V^2) for the adjacency matrix or O(V + E) if using an adjacency list. Edge cases include disconnected graphs (where some nodes will remain at infinite distance), graphs with zero-weight edges, and graphs with only one node. The algorithm's correctness is based on the greedy approach: at each step, it assumes the shortest path to the currently selected vertex is finalized and uses this to potentially find shorter paths to its neighbors. The invariant is that `dist(v)` always holds the shortest path found so far from the source to `v` among visited nodes.

Pseudocode:

FUNCTION dijkstra(graph, num_nodes, source_node):
  Initialize dist array of size num_nodes with infinity, dist[source_node] = 0
  Initialize visited array of size num_nodes with false

  FOR i FROM 1 TO num_nodes - 1:
    Find vertex u with minimum distance in dist[] among those not yet visited
    IF u is not found or dist[u] is infinity: BREAK (disconnected graph)
    Mark u as visited

    FOR each neighbor v of u:
      IF v is not visited AND graph[u][v] is not 0 AND dist[u] + graph[u][v] < dist[v]:
        dist[v] = dist[u] + graph[u][v]

  RETURN dist