CD3291 Data Structures and Algorithms Lecture Notes 1
CD3291 Data Structures and Algorithms Lecture Notes 1
com
LUnut
DA 4 -
Gcaphtnavesak-
Rapaesentation oç qnaph. Taea
GtVaph ADT- -8hoAtstVpabbs-minimum
spanning
lopological ondbang
Gpaph ADT
w e meke
collectton of
Vertices and edges
A
A qnaph is a
a Combinatton of
thzno o l a t a t y p o s
Eigtka
as
tho ab&tilac kon Vntexrs a set of nados,
and Gaaph
VeRtex,Elge
of
Ventices es mathods .
colecHon of
pata
includes
the followtng
fotlouwtnq
ADT
The
The 9naph
Sotve atex
g e t ve atox
ddd Edg2
g0tEdols
Taanspontation
hetwonk -hughuay No,
LAN, Intex ne
Compuiter nlw
-
Rpasentin ER diagnam
Databases
Gaaph Rapaas entalton
Adjacncy Matix
Adtacence ist
tAdyacend set
def_len_(self):
return self.size A B
7.
#Print the matrix
def print_matrix(self):
for row in self.adjMatrix:
B
for val in row:
print({:4).format(val),end=")
c o
print("n") Do O0.
def main():
g=Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(4,1)
8.print matrix()
if_name main
main()
self.next= None
class Graph:
def_init_(self, num):
self.V= num
self.graph
=
[None]* self.V
# Add edges
def add_edge(self, s, d):
node AdjNode(d)
node.next= self.graph[s]
sclf.graph[s] = node
node AdjNode(s)
node.next= self.graph[d)
self.graph[d]=node
#Print the graph
def print_agraph(self):
for i in range(self. V):
print("Vertex + str(i) +":", end="")
"
temp self.graph[i)
while temp:
print(">{}".format(temp.vertex), end="") C)
temp= temp.next
print(" In")
if name main_ A
V = 5
#Create graph and edges
graph Graph(V)
graph.add_edge(0, 1)
B
e
graph.add_edge(0, 2)
D
graph.add_edge(0, 3) D
graph.add_edge(1, 2)
graph.print_agraph()
PPYenax0:3 >| ( (3
Vaafar > 9 0
Vate 3 : >o
eateA
Adjacancy set.
o adjacancy uad. kist,but
T ts Yey much stmla
list, Asjont
kek ade
nstaao of u s inkad
naph Taarersals
amachantsm
9naphs,w0 noocd
classftud by atypes
on
To solvo pAoblems chn be
the graphs.T
foa txavoxing Deph fiast
saanch CDFS)
saaach (BES)
Bheaclth {iast
s2aach (DFS)
useo taavnaR oalocalz a
p i h tnst an
algoaihm
Ctaa. It ptkuti
DFS en taee
datasfau
en a qkaph as it g9until
noole one
bäanch as fa
tanget
&eaches Valong backtsacks to he
hae it
Bepii ad that bnarch
Once
baarch Q
baareh
d2archa
and&earhea
af
ho endpoksibla
he divegnce
fRom that
aom that
the pocos
fiast baahch, epeaitng
endl
tha of thdt
ntil
Aigoittm
d a o f a (eliadgtophheda)
tnea is
Callod t h e DEs taaa.
geneialid u
The'inal VAtcas ara pADcOLad
twhith tha
ôadla"in
and the numbaas of tha Vantca
DFS
caltaod
RlgoaiYhm
de bfs cVisilad,naph,nsda)
Visia.appehdtnoole)
La appand Choala)
whila qaua caaahng koopt5 risit each od4
m9uotia. pop)
PrinCm,end
foR neighbota raph in
q1 tnal a fopoloqical
topoloqical
algoei hm
0 lo ftnal a intomirg
Vbatix with no
AA Stmple V 4 i n d any s e m o v e it,alon
OAdonung
RBE thi
Venkex,and
then paint staaBeqy
eolos.wecan the qnaph The same 0
edgus aom Othe 9iaph,
giaph
with i Aest af (he a ve tor
the ndeg7rco.0f
applied lo the
T o honmali20
this tod doftné
Cu
W ) u e c o m p t a tHe
Indegae
humo2ot eoges dequeuav
a s the the n9aaph. )
yenices
O at
deqiuatu is
Indaut meve daqusuas H
Yrt 2 3 5
2
3
da topolegccalsont (@)
topaloqicallist : [1
:
topolcgiCal 9ueue [ : J
Aemaintngindeg: f3
()
hool es G.de EreAtces
=
deqeue:V7 dcgqueus:Vs
VL
( n
an
untoeighliol
unweighlãot 99napi
nap
woudd
w old
diagnam &hotwa
above pa
p aaaaarrttie
etta
a,,he
he
The b a n inrt
inRf
vexl x SLwhich
nom' o a l othea VeaHeeg. ve2Hces.
ustng
Lstng
som2
the
Shoatest pacth ot o l g Containe
riumba2n
Uo i n
nakonostad i n the on h tHoo ed ea. wbo
edh es. we
ikU
Liko k
i n t e n e s l i d
ho werah
o ueians
Only h
thene are
aae
Cwe 1pat,o aa weight "of
oeia hE "of 1
1 .
On the
on all edges wo can tell hat
ra,
CDuld QssrgnChoos2 % 0 w e hoole Slo be angh 0.
w is then a path 0f
path n o m S lo
Vs
&hontest
the 1
Th shcos the fig
(V Knnun dN
(t
e anS 6hown tn
dlga.
fiq3 uwhos2 Bhoatost path faom S is
Nowind
Now ydaticos
xactly &,By findtng aalL tha oatices adjalent ls Ynand V6
whose Shoest pat e not alneady enoLon.
193
Tritial shat VaDegtas MDacuud_2nuaLacd
y ondv pv Wrun dv Kiosn di ey kon dy
YS
Algoasthm.
He bis¢):
Sefstaatvisilis =Taue
qucue.appnd (Seif-start)
whila aheue :
Cumdntnode quOue.popto)
clorenthole.neghbas:
o nodle în
nade.visi l i
i not
nocle.nsilae-Mue
9ucue. appendCnade)
ple.pxbu -cTent nede
inede =2el f end
QuQuo .clcaaO.
Self traceAo Downloaded
s from EnggTree.com DEPASTAMENT OF
SE UMAniTIES
AD 3251-Data Design
EnggTree.com
Structures Unit:
Subject Code/Title:
qsapb Djkstaa'sAlkourhm
Shoatest path in oeahlidtn'wetqhthd qnapH' paodu
path phpaden
the
Y Knoon dv R
JU
2
Ys
Initta confiqutahbn
8taat
nodla S is Vi, The frast
t h a t the yealx k
Asuminq
n,with path lengh 0.THu
k 8ome entaies
Veatee etec to that Vi ts knosn,
Viafda
knoton Noo lo
maakool VeAtieos adjacent
The adjuulid.
be adjustaol. enttatos
neeal to Veaticos get thatn
Q n d maaked knoton
knotan.
aoliacenl cleol,and
Seleetecol, table
only V3 KS ele
Aosultinq tabt
3t
65Then, loS3T 5 8
tD *..Tho A0sulting
adjtus
lial d a n 5.
in e tupedalid down t
8houds
V is &e lecud V6ge tn gaab
Next tabto Vghouos
a0&ultinq is 3hoton tn
The inaltalta
5+16.Tho
V6 is seloclack
Hinaly
on houo tho.
tiquneT tma depenols Consida
aunning have yet lo
The whikh too
maniplal+ol ,
are ie oCIEI+/V12) -%Ive
oCEl+lvi2) -oIvP)
eaitces
entic es timne
of
total
aunnin
Ainaar è
inaaa en tha
n fha
number
n umbe o
he 2un8 n Himo
mo
Since it
edass
newn dv Vknen dy Knouon.dv
2
Y4 3
co Y4
V Y4
F Y4
Vavdael and
sdeclaud H V4 H 3
knouon
4- Knouwn dedlaredknouon
Algorithm
1-Stages of Dnkstaa's
#ImplementingDijkstra's Algorithm
def dijkstra(graph. initial):
visited initial : 0}
path defaultdict(list)
nodes set(graph.nodes)
while nodes:
minNode = None
pathedge].append( minNode)
return visited, path
Hara multtpla
Z
pannng tiues
A
A
miimum
Tuso Ualqoeithms
ane CLs Sl thisploblamn
Conneclol. Thsde
P i m s hlgoith
4Kauskalsalgoaithm.
as dejkstnals
Paums Agorithm the same
is almost finds'the
inds"the.
Algoeithm a s input and
Paems qraph
aq gnaph
t h d t q a p h which
T t (Hakes E h d t qaaph
hlgoithm
the edges
of 0. Qvmy Vertex
Sutset of that inetudes
all tha
thue among
foam
a
Cweih
woihla
minimum 8um of qaapN.
tho
has the be
fOAm0clAom
taeos that
an
(
7
Vs
Vs
(V6
Spaningfa0a
9Aaph G ano ii
mnimum
A
- -
- . G-
Y
Vs A
F F V4
F
Subject
V knoun Gy P V khon d R
VMnaun y
2
2
edgeNum=0
visited[0]=True
while edgeNum<self.vertexNum-l:
min sys.maxsize
if visited[i]
vertex Num):
forj in range(self.
if ((not visited[i]) and self.edges[i|l):
if min > self.edges[i]G]:
min self.edges[i]0]
d-j
self.MST.append([self.nodes[s], self.nodes[d), self.edges[s][d]])
visited[d] = True
edgeNum+=||
Kauskal's Alpadhm.
alqoaithm
8taa totn r disteaent tae0s.while
The
Constauchir te
minuMtem
menumcem taee spanhin ,2veay tmo
the
Jlavaithm Selec k
an eolae that has nlinimumn
Kauskal s on adals
adds that
that eolge,
it docsnot canat a eolor
Kauskals thon
and Ivl3
veight
inittallythee ane Sinqte Noolo taees in na
tha
Cye.s0 tudtaees int one.
an odge meages en
aest.Adding Vthee will be only Ono
oloorithnY is Compeud,
he al (thatt h e minimum spanninqtaod
and
Ganph
Ege Waight Action
Axaptid
Aeceptod
2
Accaptod
Accepted
, Recpd
Raectod
Actaptod
16) Reted
Aecoptod
Action e kzuskals
algottinmon&
veagn
Code/Tite:
AD Unit:
Subjcet
EnggTree.com
- 2
.
kauska" algoeihm afterRach &tag
class Giraph
def init_(self. vertex):
self V vertex
selfgraph-[1
v. w):
def add odgc(self, u,
self.graph.append((u, v, w])
def scarch(self. parent, i):
ifparentfil==i:
return i
returm self.search(parent, parent[i])
rank. x, y):
def apply_union(self. parent,
xroot self.search(parent. x)
yroot self.scarch(parent.y)
if rank xroot< rankly root:
parent[xroot] = yroot
else
parent(yroot aroot
rank aroot] += |
def kruskal(self):
result= []
i ,e 0,0
self.graph =
sorted(self.graph, key=lambda item: item[2))
parent [
rank []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e< self.V - 1:
u. v, w = self.graph|i
i=i+l
a self search(parent, u)
y self.search(parent. v)
ifx=y
eetl
resultappend([u, v, w])
selapplniontparent,rank, x, y)
for u, v, weight in result:
print("Edge:",u, v,end=" ") print("-",weight)