Skip to content

Commit fce6d0c

Browse files
committed
optimized dijktra's
1 parent ad2a94f commit fce6d0c

1 file changed

Lines changed: 8 additions & 7 deletions

File tree

Graph/dijkstra.cpp

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ A minimum distance of src from every other node present in graph with all non-ne
33
Complexity for dijktra's Algo -> O((V + E) log V)
44
E-Edges V-Vertices
55
6+
We may add same node multiple times, hence total elements in a heap might be E. Hence, log(E).
7+
Intreasting thing is to E = V*(V-1) => 2*log(V).
8+
69
Slight modification: Think of adding a virtual node which joins an edge to each node. [Similar to multi source BFS]
710
811
Dikjtras can be applied 3-4 times... you reverse graph... node a to src and dest dist
@@ -43,17 +46,15 @@ void dijktra(int src)
4346
int curr = pq.top().second;
4447
pq.pop();
4548

49+
// Optimized to not traverse children if minDist which was encountered earlier was better
50+
// This helps avoid traversing children if we already have a miniDist smaller traversed earlier
51+
if( curr > min_dist[curr])
52+
continue;
53+
4654
for(auto u : adj[curr])
4755
{
4856
int next = u.first;
4957
int d = u.second;
50-
51-
// There are multiple copies of same node in pq with different weights
52-
// if min_dist[node] is less than d then there is no way that any other node
53-
// which can be reached via this path with lesser dist.
54-
// NOTE: Removing this condn will allow negative weights in Dijkstra's algo
55-
if(min_dist[next] < d)
56-
continue;
5758

5859
//If previous distance is more than the new distance
5960
if(min_dist[next] > min_dist[curr]+d)

0 commit comments

Comments
 (0)