Graph Data Structure
A graph can be defined as group of vertices and edges that are used to connect these vertices.
A graph can be seen as a cyclic tree, where the vertices (Nodes) maintain any complex
relationship among them instead of having parent child relationship.
Definition
A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of vertices
and E(G) represents the set of edges which are used to connect these vertices.
A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C), (C,E), (E,D),
(D,B), (D,A)) is shown in the following figure.
Directed and Undirected Graph
A graph can be directed or undirected. However, in an undirected graph, edges are not
associated with the directions with them. An undirected graph is shown in the above figure
since its edges are not attached with any of the directions. If an edge exists between vertex A
and B then the vertices can be traversed from B to A as well as A to B.
In a directed graph, edges form an ordered pair. Edges represent a specific path from some
vertex A to another vertex B. Node A is called initial node while node B is called terminal
node.
A directed graph is shown in the following figure.
@ Dr. Ganesh Khekare
Graph Terminology
Path
A path can be defined as the sequence of nodes that are followed in order to reach some terminal
node V from the initial node U.
Closed Path
A path will be called as closed path if the initial node is same as terminal node. A path will be
closed path if V0=VN.
Simple Path
If all the nodes of the graph are distinct with an exception V0=VN, then such path P is called as
closed simple path.
Cycle
A cycle can be defined as the path which has no repeated edges or vertices except the first and
last vertices.
Connected Graph
A connected graph is the one in which some path exists between every two vertices (u, v) in
V. There are no isolated nodes in connected graph.
Complete Graph
A complete graph is the one in which every node is connected with all other nodes. A complete
graph contain n(n-1)/2 edges where n is the number of nodes in the graph.
@ Dr. Ganesh Khekare
Weighted Graph
In a weighted graph, each edge is assigned with some data such as length or weight. The weight
of an edge e can be given as w(e) which must be a positive (+) value indicating the cost of
traversing the edge.
Digraph
A digraph is a directed graph in which each edge of the graph is associated with some direction
and the traversing can be done only in the specified direction.
Loop
An edge that is associated with the similar end points can be called as Loop.
Adjacent Nodes
If two nodes u and v are connected via an edge e, then the nodes u and v are called as neighbours
or adjacent nodes.
Degree of the Node
A degree of a node is the number of edges that are connected with that node. A node with
degree 0 is called as isolated node.
@ Dr. Ganesh Khekare
kepre serdatron ef Ghph in
Adjaceny
Aäjacenty
T is a mettir alnJ)
where n she numb
vertrtes
4fariL]=l,# i4ja
Dr. qunsh ubarc
His
fek each vetiep one linke k
rbanet khekae
2
3
Spasje
2 BFS Brca dth
DES
Al
Cor Ganesh kheka
I3 2 5 6
Verties
tnvitid Veutiey
Acady iild veies
meLous
BFS Pseudocode
BFS (G, s) //Where G is the graph and s is the source node
let Q be queue.
[Link]( s ) //Inserting s in queue until all its neighbour vertices are marked.
mark s as visited.
while ( Q is not empty)
//Removing that vertex from queue,whose neighbour will be visited now
v = [Link]( )
//processing all the neighbours of v
for all neighbours w of v in Graph G
if w is not visited
[Link]( w ) //Stores w in Q to further visit its neighbour
mark w as visited.
@ Dr. Ganesh Khekare
DES sta
Consider Same gaph as Aien 19 .
Qne
inseitedin ehack
DES means e tare to
deph wntend and
ho
báckdnakig
do bocktrackig
ODr-Ganah khekhe
Resulli-o L32165
lee als DES taeneja/ nesu
ne ossible
DFS Pseudocode
DFS-iterative (G, s): //Where G is graph and s is source vertex
let S be stack
[Link]( s ) //Inserting s in stack
mark s as visited.
while ( S is not empty):
//Pop a vertex from stack to visit next
v = [Link]( )
[Link]( )
//Push all the neighbours of v in stack that are not visited
for all neighbours w of v in Graph G:
if w is not visited :
[Link]( w )
mark w as visited
DFS-recursive(G, s):
mark s as visited
for all neighbours w of s in Graph G:
if w is not visited:
DFS-recursive(G, w)
@ Dr. Ganesh Khekare
Difference Between BFS and DFS
Key BFS DFS
BFS stands for Breadth DFS stands for Depth First Search.
Definition
First Search.
BFS uses a Queue to find DFS uses a Stack to find the shortest
Data structure the shortest path. path.
BFS is better when target is DFS is better when target is far from
Source closer to Source. source.
As BFS considers all DFS is more suitable for decision tree.
Suitability for neighbor so it is not suitable As with one decision, we need to
decision tree for decision tree used in traverse further to augment the decision.
puzzle games. If we reach the conclusion, we won.
Speed BFS is slower than DFS. DFS is faster than BFS.
Time Time Complexity of BFS = Time Complexity of DFS is also
Complexity O(V+E) where V is vertices O(V+E) where V is vertices and E is
(Same) and E is edges. edges.
BFS requires more memory DFS requires less memory space.
Memory
space.
Tapping in In BFS, there is no problem In DFS, we may be trapped into infinite
loops of trapping into finite loops. loops.
BFS is implemented using DFS is implemented using LIFO (Last In
Principle FIFO (First In First Out) First Out) principle.
principle.
@ Dr. Ganesh Khekare
Tyes ef Edas in DFS Tiavehsaf.
9 Tiee Edge members o DS Trayerde
) Foroa Edje CiCl) blse, yo
and thore Is a pth hon, 1 y
back ioard Fdge
befere and thne i a tt Elom
oss y is
Cros ede Ahere
wherehe is no pet
from DrGanesh Khekaye
Xy wil be decioled based on
Parul
University edoe hon
37
I/26
(d
15/18
92
Dy Ganesh khekase
hauts /kpeauig/ Diteueag Tine
Thee Edas
Dinimun Sannig Tae e(mS)
G'(v E') Giapl can hare nens
wheru, v=V
F'CE - mIT
ds conted
Giren
mST is
(DrGanesh Kickaye
3
ede tso anig
the dittinc
then will he
-An-2cnpltealseked graph canhae
Connekeo
does ned hade
Elbm
he cay con
Mo
2Mas Can be ssaoa
-Remove all he
Renterne parale) ethes.
-Choose
- Chekout alpbiany
the oudgo. edoes Tomm
o. min. ce
Checkout all the outgeig edus tlom
all He aveilablo hoes ad selc ni
hode
inimu9
()Dr Ganeh khekare
3
2
8
2
Final Arguer onsdeadsoAas soNe vert
7
3
2
2
Pseudocode of Prim’s Algorithm for MST
prim(graph):
# Initialize an empty set to hold the vertices in the minimum spanning tree
mst = empty set
# Select the first vertex to start the tree
startVertex = first vertex in graph
[Link](startVertex)
# Initialize the set of edges to consider
edges = edges connected to startVertex
# Iterate until all vertices are in the minimum spanning tree
while mst has fewer vertices than graph:
# Find the minimum edge in the set of edges
minEdge, minWeight = findMinEdge(edges)
# Add the vertex to the minimum spanning tree
[Link](minEdge)
# Add the edges connected to the vertex to the set of edges to consider
for edge in edges connected to minEdge:
if edge is not in mst:
[Link](edge)
# Remove the minimum edge from the set of edges to consider
[Link](minEdge)
# Return the minimum spanning tree as an array
return mst as an array
@ Dr. Ganesh Khekare
Ac=3
3
|2
Hhis abutog
in eit one Cnly
tosnga hgyihat nshculd
g cdechelpoiat,
the Select
nde inckasik seshk
in
pmalle ard leozs -Kenpeall
the
kauikal
Pseudocode Kruskal’s Algorithm for MST
KRUSKAL(G):
A=∅
For each vertex v ∈ G.V:
MAKE-SET(v)
For each edge (u, v) ∈ G.E ordered by increasing order by weight(u, v):
if FIND-SET(u) ≠ FIND-SET(v):
A = A ∪ {(u, v)}
UNION(u, v)
return A
@ Dr. Ganesh Khekare
Difference between Prims and Kruskal Algorithm
Sr. Prim’s Algorithm Kruskal’s Algorithm
No.
1 This algorithm begins to construct This algorithm begins to construct the
the shortest spanning tree from any shortest spanning tree from the vertex
vertex in the graph. having the lowest weight in the graph.
2 To obtain the minimum distance, it It crosses one node only one time.
traverses one node more than one
time.
3 The time complexity of Prim’s The time complexity of Kruskal’s algorithm
algorithm is O(V2). is O(E log V).
4 In Prim’s algorithm, all the graph Kruskal’s algorithm may have disconnected
elements must be connected. graphs.
5 When it comes to dense graphs, When it comes to sparse graphs, Kruskal’s
the Prim’s algorithm runs faster. algorithm runs faster.
6 It prefers list data structure. It prefers the heap data structure.
@ Dr. Ganesh Khekare
Parul
University Facuty of Engineering &Tehilg
Ojkstra Algovihm/Srgloae Shaksi
Path 6redy Methidi
du)
2/.
6
2
Shotest Pitance eto 2
Oto 3 19
3
f)Darsh khekare
A
C
e5t
DB A
ACB 0 - 9
543+|=0,
latth
BCA
A CB
when
wwnk
nat
mey
oi
may
Pseudocode for Dijkstra Algorithm
@ Dr. Ganesh Khekare