Graphs PC
Graphs PC
Intro to Shortest
Path Algorithms
Path Algorithms
Session Contents
Dijkstras Bellman Ford Floyd Warshall
Algorithm Algorithm Algorithm
DIJKSTRA
ALGO
Try it yourself using the link
DIJAKSTRA
It works on both Directed and Undirected
graphs.
Select Minimum distance vertex and
Discard marked vertices.
Data Structure to use : Priority Queue or
Sets
Priority Queue : Insertion and Deletion
O(logn)
Declaring a priority queue
of pairs on minimum priority
BELLMAN FORD
ALGO
Try it yourself using the link
BELLMAN FORD
It works on both Directed and
Undirected graphs.
Select the edges one by one and
update the distances if possible.
Updating the distance due to an
edge if possible : Relaxation of Edge.
Repeat the process n-1 time :)
Declaring a struct to store
the properties of the edge
Checking for
disconnected
components
Time Complexity : O(n*m)
ADVANTAGE
Works on Negative Edge Weighted Graphs
too
We can detect a negative cycle in the graph
using this Algorithm
Note that in case there is a negative cycle
then the minimum distance of the vertex in
the cycle becomes (-infinity)
DETECTING NEGATIVE
WEIGHT CYCLE
Iteration 0 : Iteration 1 :
dist(h) = 0 dist(h) = -3
dist(i) = inf dist(i) = 2
dist(j) = inf dist(j) = 5
Iteration 2 : Iteration 3 :
dist(h) = -8 dist(h) = -13
dist(i) = -3 dist(i) = -8
dist(j) = 0 dist(j) = -5
CSES : HIGH SCORE
FLOYD WARSHALL
Make a distance matrix, where dist[i][j]
stores shortest distance between i and j.
Initialise it with dist[i][i] = 0 and if
there is an edge b/w u and v of weight c,
then dist[u][v]=c & dist[v][u] = c.
Go over the vertex list, let's say we are at
vertex k.
For every pair of vertices, update dist[i][j]
with dist[i][k]+dist[k][j] if it is smaller.
VISUALIZING
THE
FLOYD WARSHALL
ALGO
Try it yourself using the link
ADVANTAGE
Very easy to code and implement.
Finds distance of each vertex from every
other vertex.
Works on Negative Edge Weighted Graphs
too.
We can use it to detect negative cycles in
the graph too.
We can even find the sequence of vertices
in the shortest path between every pair of
vertices.
Drawback: Takes O(n^3) time to run.
CSES : SHORTEST PATH II
THANK
YOU