Marking Visited Nodes
In addition to the distance array, Dijkstra's algorithm also maintains a visited array to keep track of which nodes have been visited during the algorithm's execution. The visited array is typically initialized as follows:
- Set all elements in the visited array to
false
, indicating that no nodes have been visited yet.
The visited array is used to ensure that the algorithm does not revisit nodes that have already been processed, as this would lead to incorrect results.
Here's an example of how to initialize the visited array in Java:
import java.util.Arrays;
public class DijkstraAlgorithm {
public static void main(String[] args) {
int numNodes = 5;
boolean[] visited = new boolean[numNodes];
Arrays.fill(visited, false);
// Print the initialized visited array
System.out.println("Initialized visited array: " + Arrays.toString(visited));
}
}
This code will output:
Initialized visited array: [false, false, false, false, false]
In the above example, we have a graph with 5 nodes, and we initialize the visited array with false
values for all nodes, indicating that none of the nodes have been visited yet.
As the algorithm progresses, the visited array is updated to mark the nodes that have been processed. This helps the algorithm avoid revisiting these nodes and ensures that the shortest paths are found efficiently.
By properly initializing both the distance array and the visited array, Dijkstra's algorithm can effectively solve the shortest path problem in a weighted graph.