DATA STRUCTURE & ALGORITHM
GRAPHS
ee ——=_—
¢'
gah is @ palettes tool used to represent
+ AS networks, data structures, scheduling, compaten
‘ere the relationship between the objects in the eee : dominant a. Gaeta:
pes of graph: A graph often symbolized as G can be of two types: =
* undirected graph: where a pair of vertices representing an edge is unordered.
cted graph: where a pair of vertices representing an edge is ordered.
raph Traversal: A graph can be traversed in two wajs, :
epi ist search traversal: often analog
preadth first search traversal:
@ physical problem. tt is also used to
Tay 80s to pre-order traversal of an ordered tree.
often analogous to level-by-level traversal of an ordered
tee ,
|, sanning Tree: Given a connected, undirected graph, a spanning tree of that graph is a sub
h which is a tree and connects all the vertices together. A single graph can have many
diferent spanning trees. We can also assign a weight to each edge, which is a number
sgesenting how unfavourable it is, and use this to assign a weight to a spanning tree by
computing the sum of the weights of the edges in that spanning tree.
|. stortest Path: In graph theory, the shortest path problem is the problem of finding a path
feween two vertices in a weighted graph such that the sum of the weights of its constituent
sis minimized,
TBemest important algorithms for solving this problem are:
Diista’s algorithm solves the single-source shortest path problems.
inan-Ford algorithm solves the single source problem if edge weights may be negative.
sarch algorithm: solves for single pair shortest path using heuristics to try to speed up
‘esearch,
Multiple Choice Type Questions
‘vertex, removal of which makes a graph disconnected is called [WBUT 2007]
‘Pendant vertex b) bridge
‘culation point d) colored vertex
Mr (c)
Mt
[WBUT 2007, 2018]
4
‘x of indegree zero in a directed graph is called
‘atulation point b) sink
‘ated vertex ) root vertex
°() 3
ity 7 Z [WBUT 2007, 2012, 2016)
engl Matrix of a digraph is sy ammetsen ae
Sete d) none of these ee
DSA-95
Scanned with CamScannerret traversal Of 29FAph? (Way
POPULAR PUBLICATIONS
for breadth fis oe iT,
is used
4. Which data structure ! OoRbme of these
‘Stack
+ Both stack and queue
Answer: (b)
rected graph is waur
b) Asymmetric matrix
i
jacency matrix of an Un
5, The adjace! d) None of these
1a) Unit matrix
¢) Symmetric matrix
“Answer: (€) :
we
6. BFS ‘9s bofore moving to the other vertex Bur:
‘)_ scans all incident eda
b) scans adjacent unvisited ve
s backtracking
tex as soon as possible
c) is same as
d) none of these
Answer: (b)
7. Anon-planar graph with minimum number H oe fa r [WBUT 2008,
i edges, 4 vertices vai
a) 9 edges, 6 verte 4) 9 edges, 5 vertices
c) 10 edges, 5 vertices
‘Answer: (c)
have at least
8. Any connected graph with x vertices must
c) x edges
a) x+ edges _b) x-fedges
Answer: (b)
|
9, Maximum number of edges in a n-node undirected graph without sel loops
a) » ed one? wan
Answer: (b)
10. re de .
a) a mini it s
seme es
[WBUT 2010, 2
11.A onviete directed graph of 5 nodes has.
a) b) 10 °)
Answer: (b)
12. A vertex with degree one in a graph is called
aleaf
Answer: (b) ) pendant vertex _ e) end vertex
DSA-96 /
?
aca ea
implement
13 Ty stack
answer (2)
gjacency ma
14 unit matrix
3 asymmetric
answer? (P)
45. What is the su
a) 19
b) 20
5
d) none of the:
answer: (8)
46, The adjacency
a) Unit matrix
c) Symmetric
Answer: (c)
17. A path is
a) a closed wa
b) an open wal
c) an open wal
d) a closed wa
Answer: (c)
'
1. Deseri :
hee be Krusk:
Kfuskat’s algorithm
ie connected we
mmigitnst includes «
immized. If the g
ct spanning
itn Ple of a greedy
+ “OKs as follows:
+ eate a forest
whi @ set S co
Tene Sis noner
Ove an edge
Scanned with CamScannerTy
ip toumstement DFS which data ‘URE & ALGORr
e
ay stack b) Queu
structure
is general
lly used’
3 (2) ?
ost
©) Both (a) & (by [WBUT 2013]
: 4d) None of these
acency matrix for a digraph is
Hay ynit matrix
3} asymmetric matrix Sermmaviomatig MONT
ee | 4) none of these
hat is the Sum of the degree:
, $ of all the vertices in the following graph?
; ‘ . 4 (BUT,
. [WBUT.2017]
35
none of these |
aaswer: (2)
4g. The adjacency matrix of an undirected graph is
aaa H Advnimeticinatia? ee
¢) Symmetric matrix ese ated
Answer: (c)
41, Apath is weur 20171
b)an open walk with no vertex repetition
¢) an open walk with no edge repetition
djaclosed walk with no edge repetition
Answer: (€)
inimal spanning tree algorithm.
f
|
3)a closed walk with no vertex repetition \
|
|
'
\.Describe Kruskal’s mi [WBUT 2008, 2018]
Aaswer:
Knwskal's algorithm is an algo!
‘ora connected weighted graph.
tee that includes every vertex,
Tinimized, If the graph is not
Tinimum spanning tree for eacl
ample of a'greedy algorithm.
Yorks as follows: vertex inthe grapis @ separate tree
‘ Ceate a forest F (a set of trees), where eae :
* create a set § containing all the ed8es !° thee
« Shile Sis nonempty
move an edge with mi
Node
Pop 1 = — Z | | Step 2 -> Node
Visit 3 5 : [| [Step 3-> Node
Visit 7 37 124563 HL [Step 4> Noa
Remove 7 - 1245637 ae {Step 5 > e:
3 : Nod
Remove3 | - i |Step 6
; D6 -> Nod
Done “dL |Step 7-5 Noge
lode
Required DFS is 1245637.
— Th
_'©Steps involve
DSA-100
Scanned with CamScanner* DATA'STRUCTURE & ALGORITHM.
oes traversal we employ the followin
¢OF ule 1 — Visit the adjacent unvisi F !
fo : in need nvisited vertex, Mark it as visited. Display it.
Rule 2 — If no adjacent vertex is found, Pop uy I
u ; I ip a vertex from the stack. (It
will pop up all the vertices from the Stack, which do not have adjacent
vertices.) :
Rule 3 — Repeat Rule 1 and Rule 2 until the stack is empty.
i rules using stack
sing the aoe svat at get can get the following traversal when starting with A:
HI
ABEC
FS/DFS Algorithms and find out the path of the.given graph:
z.apply 5 aiven grsPh WBUT 2018]
\
mes involved-in breadth first traversal are as follows:
[Search Steps i : ,
ee 1->Node A
|Sep2-> Node B
[Sep 3 > Node C
\Sep 4-> Node F
\Seps>NodeG
[Step 6 > Node D
\Sep7-> Node E ee
‘ as follows:
Testeps involved in depth fst traversal
= :
Sep > Node A
'892.> Node B
'Sep3 > Node C
th? Node F
‘i S>Node D
Ieo> Node G
°7->.Node E
Scanned with CamScanner—————
soouaneueucations
ige classification
of DFS algorithm. [MODEL QUegy,,
d G we can ; 3
Deseribe the E 5 of graph Put each ga A
dower’. 2 gave} Aner aD Seep Pa pirst Se
Consider a directed grap! pep! ed tree For
ordemute 12 IEP
‘one of four classes
on the stack.
1. Aree edge isan
2, A buck edge connec
backedge.
3. A forward edge is 2 70"
fer i ddge in graph G. It
4, Across edge is any other cae no
‘i tree.
edge ina Des: ree ncestor in a DFS-tree. Note that a set,
ts a verte
edge that connects a Vertex tO a descenden in,
yn-tree
connects vertices in two differen,
her of which is the ancestor afyye
al
tree or two, vertices In i aa mr
to adescendant wee
ven gra
1 ATree Eee wr
Rule 1: Visit al
vertex, and insert
4.A Cross Edgetoa
rae we Rule 2: If there i
oe current vertex an
Rule 3: Repeat R
Breadth-first sear
explores all the né
unexplored. neight
The time complex
edge will be explc
Depth-first search
oF graph. Intuitive
case) and explore
complexity is also
Any particular DFS or BFS of a directed or un-directed graph, each edge gets cl
as one of the above, :
In a DFS of an undirected graph, every edge is either a tree edge or back edge. Herta
cross edge goes to a higher numbered or rightward vertex. The reason behind the
algorithm is so important is that it defines a very nice ordering of edges of the graph.
"Part:
There are three we
Describe BFS algorithm.
Scanned with CamScannerert
est Search: DFS of a graph is
ofl Syee Fora given graph the DFS will ha
tie 1: If possible, visit an adjacent unyi
+ Mi pe stack.
ore: If Rule 1 fails,
logous to the
ye the followin;
sited vertex,
Per-osder traversal of an
ig rules,
; mark it visited, and push it
: then if i
wate 2 possible
we a PoP a vertex off the stack follow Rule 1
: Repeat Rule | i '
: ule 3! Rep and Rule 2 until the all the vertices are visited.
: he 2
in First Search: BFS of a graph is analogous to level-by-level traversal of an
er ee F
sfaaiven graph the BFS will have the following rules,
. Visit all the next unvisited verti i i
ule: Vis ext ertices (if any) that is adjacent
venex, and insert them into a queue one at a time on every visit. et ne
yule2: If there is no unvisited vertex, remove a vertex from the Queue and make it the
ment vertex and then follow Rule 1.
fule3: Repeat Rule | and Rule 2 until the all the vertices visited,
radth-first search (BFS) is a graph search algorithm that begins at the root’ node and
agloes all the neighboring nodes. Then for each of those nearest nodes, it explores their
sraplored neighbor nodes, and so on, until it finds the goal.
Tetime complexity can also be expressed as O( |E| + |V|) since every vertex and every
‘ige will be explored in the worst case.
Dgtiitst search (DFS) is an algorithm for traversing or searching a tree, tree structure,
‘cgaph, Intuitively, one starts at the root (selecting some node as the root in the graph
)and explores as far as possible along each branch before backtracking. The time
‘plexity is also given by O(| Z| +| V1)-
Part:
mr three ways by which graphs can be rel
‘acency matrices.
N ‘Gsceney list.
‘jacency multilists
presented in memory:
: i matrix is a 2D
4 Adaeency matrices: For a sriph G with 9 vertices the adjacency
any
"Y with n x n element.
ish ls ithere isan edge between |
O.ifthere is no edge between |
psA-103
Scanned with CamScannerPOPULAR PUBLICATIONS
Fordirected, seth an edge directed | &)
Exam
Ali ere aceon Mate
lfo J 1 1g @
: 2) ot ko
VP 3: [ig Be OT. ay
CX C) 4 |e too ca @)
/ > slo 11
er) Undi
Undirected graph “2 3 als
QO. Ve po° 110
S<] OD 20011 }
3b oo1]
G0) 4}i 000]
Directed graph 7 ;
The adjacency matrix for an undirected graph is symmetrical i.
zero, ‘
Advantage: It is possible to determine whether an edge is connecting two vericat
not.
Disadvantage:
+ It requires n x n memory locations, If the graph is not complete, there wil
number of zero entries & this will waste the memory. area. To avoid't!
adjacency list method is used,
There will be two entries for the same edge. This information is redundant
Drawbacks: Wh
Pointers, which c:
iit) Adjaceney
Braph, it is cle
and another
information py
list form a path between the head
from that head node.
ructure
mo
V, y.*8fielg
PL Ver
+P, * Srtex,
~ Meident
DSA-104
Scanned with CamScannerHead nodes
Directed graph,
: When a graph is large, it is necessary to handle to many numbers of
hinters, which can be complex.
djacency list representation of an undirected
ied by two entries, one is list Vi
'} Agjacency Multitist: From the a
braph it is clear that each edge (Vi, Vj) is represent
and another is list Vj. This is ‘unnecessary wastage Of the memory, as the '
nodes (1,2)= (241)- :
the nodes are
,lirmation present is same at both the
Noid this, the adjacency multilist is us
amongst the several lists.
7 method for each edge of the graph, there will be exactly one ae
1 fd he information about two Fvoie ncceg 10 whieh 115 10-5 ent.
2: structure with this representation will
ee Le
sed, Using: this representation,
But this node
Pi
As
Vy 2etiela
Nyoventex
Incident paths :
psa-105
Scanned with CamScannerPOPULAR PUBLICATIONS
mis a one bit mark field th
tis Com
ate whether or not th
© cag
h
i wha
Show that the S
hat is used to indict
examined,
Consider the following 81
gnow that the n
Total distinct edges are: gaan)
{vie Vale {Wis Vas {Vas Vas {vz Vade {8 Vb (Va V3) & (yy, yg re
S) Aggy answer?
t, because this is an undirected graph,
. fe part: A grap!
vertices: :
3! Part: The nun
Degree of a verte:
oop counted twic
summation is an
edges represent the same informat
iilist representation is as follows
The adjacency mul
ut vie} ve | Ne [Ny
3 Ml
(i «De DSN
Va
Tj vi] ve P NIL] Ny calculate degree 0
. ~The tat is nothing but
2. A rat has ent
v2 | vw [NILTNG boxes are open
Tease 4 res
4 MI -
Riis » (CIEE RY Be"
aN Ns Answer:
Verex2: :
Wand ins NNN wf [NL Ne fet crest kerboa
Vere $:N7=Ng NSN vi * *4 checkerboard,
[vs] NIL[NIL,
its cost,
Answer:
The tree has ed
Costis 8. 8S AD» BD. CD, CE and BF,
b) Draw the minimum ci fr a
im i ni
‘ost spanning tree for the graph given bi d
ven below and
Scanned with CamScannerUt
js Complete Graph? = me
wna f di
ae ‘nat the sum of degree [WeUT 2009}
of all
the vertices in a graph is always even.
i [WBUT 2009]
. OR, «
thatthe number of vertices of odd degree in a finite graph
graph is even.
[WBUT 2017]
n.
[WBUT 2018]
of
OR,
pot? that the number of odd degree vertices in a graph is always
" ever
gave rer i i
pact: A graph is said to be complete if there exist an edge between every pair
ies: :
jiports The muamber of degree vertices in a graph is always even:
ree ofa vortex 18 cei as no. of edges incident on-a particular vertex with the self
bop counted twice a it wale the sum of degree of all the vertices. Now, this
fration is an even number, because each edge contributes twice when we”
slate degree of different vertices. Now, if we take the summation of alte bare
itis nothing but the twice the number of edges S'd(v,)= 2e => even number
iArat has entered a checkerboard maze through one coiner, whose the white
tures are open and black boxes represent obstacles. lop _an algorithm. by
stich the rat can exit the maze through the opposite c Clearly explain the
tensentation of the maze and any specific data structure you have used for the
dgorthm. [WBUT 2011} .
aaswer: aan
Little checkerboard maze be represented by the figure below. For simplicity we show a
‘checkerboard. AG 83)
(0.0) G.0) =
Tee maze can be re xi dimensional array. Since black boxes are
resented by a nx two al s
‘braces, the rat will only travel through white boxes. So the best path to follow will be
diagonal, :
eth will be as follow:
ihe
Ugh AG I)
ile(i