Dijkstra Algorithm
✅ Dijkstra Algorithm
weighted graph find shorest path
⭐️ Keyword
weighed graph
✅ Time complexity
Adjacent Matrix: O(N^2)
Adjacent List: O(N*logN)
✅ Code
- array to save distance, if visited
1
2
int[] distance;
boolean visited;
- initialize distance to max
1
2
3
for(int i = 1; i <= n; i++){
distance[i] = Integer.MAX_VALUE;
}
- initiate starting node distance, visited
1
2
distance[start] = 0;
visited[start] = true;
- check if visited, and set distance of the node
1
2
3
4
5
for(int i = 1; i <= n; i++){
if(!visited[i] && map[start][i] != 0) {
distance[i] = map[start][i];
}
}
- find the node that has not been visited, find min distance node
1
2
3
4
5
6
7
8
9
10
11
int min = Integer.MAX_VALUE;
int midx = -1;
for(int i = 1; i <= n; i++){
if(!visited[i] && distance[i] != Integer.MAX_VALUE) {
if(distance[i] < min) {
min = distance[i];
midx = i;
}
}
}
- check visited array, reset minimum distance with root node
1
2
3
4
5
6
7
8
visited[midx] = true;
for(int i = 1; i <= n; i++){
if(!visited[i] && map[midx][i] != 0) {
if(distance[i] > distance[midx] + map[midx][i]) {
distance[i] = distance[midx] + map[midx][i];
}
}
}
💡 Reference
This post is licensed under CC BY 4.0 by the author.