Area 2.3 : Dijkstra
Example :
Figure 5.1 : Dijkstra
Dijkstra is the same type as SPFA.
But it can’t solve the graph with an edge with minus weight.
For the algorithm, we need two arraies and a priority_queue.
Also, we need to find the distance between 1 and other point.
Step 1 : set the vis[1]=1, dist[1]=0 and push (0, 1) into pq.
Then, pop pq and get (dst, c) and relax node c.
0 | 4.16 | inf | inf | inf | inf | inf |
array vis[]:
1 | 0 | 0 | 0 | 0 | 0 | 0 |
priority_queue pq:
(0, 1) |
(Commect : (i, j) in pq : i : distance, j : current node.)
Table 5.1-a : Dijkstra(a)
Next, we push all node v((1, v) is in E) that vis[v] is 0 (Here is 2).
So, we push (4.16, 2) into pq.
(4.16, 2) |
Table 5.1-b : Dijkstra(b)
Repeat Again :
0 | 4.16 | 8.86 | inf | inf | inf | 10.04 |
array vis[]:
1 | 1 | 0 | 0 | 0 | 0 | 0 |
priority_queue pq:
(8.86, 3) | (10.04, 7) |
Table 5.1-c : Dijkstra(c)
And again :
0 | 4.16 | 8.86 | inf | 13.32 | 14.11 | 10.04 |
array vis[]:
1 | 1 | 1 | 0 | 0 | 0 | 0 |
priority_queue pq:
(10.04, 7) | (13.32, 5) | (14.11, 6) |
Table 5.1-d : Dijkstra(d)
Pop again, we got node 7.But it has no edges to relax.
So we pop over again and got node 5. Edge (5, 4) can relax.
0 | 4.16 | 8.86 | 18.68 | 13.32 | 14.11 | 10.04 |
array vis[]:
1 | 1 | 1 | 0 | 1 | 0 | 1 |
priority_queue pq:
(14.11, 6) | (18.68, 4) |
Table 5.1-e : Dijkstra(e)
Then after pops, we got node 6 and 4.They both have no edges to relax.
Now, we got all the sp from 1 to any node again.
This is Dijkstra.
Given Score :
Difficulty : 2
x Basic Score : 81
Score : 426
All Figures in the passage :
http://59.60.22.18:2500/wordpress/wp-content/uploads/2024/01/C02_Figures.zip