1
Graph and its representations November13,2012
Gr aphi sad at as t r u ct ur et hatc ons i s t soff ol l o wi ngt woc omponent s : 1. Afi ni t es etofv er t i c esal s oc al l edasnodes . 2. Afi ni t es etofor der edpai roft hef or m( u,v )c al l e da se dge.Th epai ri sor der edb ec aus e( u,v )i sno ts ameas ( v ,u)i nc as eofdi r ec t edgr aph( di gr aph) .Thepai roff or m( u,v )i ndi c at est hatt her ei sanedgef r om v er t e xut o v er t e xv .Theedge sma ma yco nt ai nwei ght / v al ue/ c os t . Gr a ph sa r eu se dt or e pr e se ntma nyr e al l i f ea pp l i c at i o ns :Gr a ph sa r eu se dt or e pr e se ntn et wo r k s . Th en et wo r k s ma yi nc l udepat hsi nac i t yort el ephonenet wor korc i r c ui tn et wor k .Gr aphsar eal s ous edi ns oc i al ne t wor k sl i k e l i nk edI n,f ac eboo k.Fore x ampl e,i nf ac eboo k,ea chp er s oni sr e pr e sent edwi t haver t e x( ornode ) . Eac hnodei s as t r uc t ur eandc ont ai nsi nf or mat i onl i k ep er s oni d,name,gend erandl oc al e.Thi sc anbeea si l yv i e wedb y ht t p: / / gr aph. f ac ebook . c om/ bar nwal . aas hi s h wh er eb ar n wa l . a as h i s hi st h ep r o fi l en ame .Se et hi sf o rmo r e appl i c at i onsofgr aph. Fol l o wi ngi sanex ampl eundi r ec t edgr aphwi t h5v er t i c es .
Fo l l o wi n gt woa r et h emo s tc o mmo mm nl yus e dr e pr e s en t a t i o nsofg r a ph . 1. Ad j a ce nc yMa Ma t r i x 2. Ad j a ce nc yL i s t Ther ea r eot herr ep r e s ent at i onsal s ol i k e,I n ci den ceMat r i xa ndI n ci denc eLi s t .Thec hoi c eoft hegr aph r epr es ent at i oni ss i t uat i onspec i fi c.I tt ot al l ydependsont het y peofoper at i onst obeper f or medandeas eof u s e . Adj acencyM Ma at r i x: Ad j a ce nc yMa Ma t r i xi sa2 Da r r a yofs i z eVxVwh er eVi st h en umb ero fv e r t i c e si nagr a ph .L ett h e2 Da r r a ybe adj [ ] [ ] ,as l otadj [ i ] [ j ]=1i ndi c at est hatt her ei sanedgef r om v er t exit ov er t exj .Adj ac enc ymat r i xf orundi r ec t ed gr aphi sal wa yssy mmet mm r i c .Adj ac enc yMa Mat r i xi sal s ous edt or epr es entwei ght edgr aphs .I fadj [ i ] [ j ]=w,t hen t her ei sanedgef r om v er t e xi t ov er t e xj wi t hwei ghtw.
2
Th ea dj a c en c yma t r i xf o rt h ea bo v ee x a mp mp l eg r a phi s :
Ad j a ce nc yMa Ma t r i xRe pr e se nt a t i o no ft h ea bo v eg r a ph Pr o s : Re pr e se nt a t i o ni sea si e rt oi mp l e me me nta ndf o l l o w.Re mo mo v i n ga ne dg et a k esO( O( 1 )t i me .Qu er i e sl i k e whe t hert her ei sanedgef r om v er t e x‘ u ’t ov er t e x‘ v ’ar eeffic i entandcanbedoneO( O( 1) . Cons : Co ns u me me smo mo r es pa c eO( V^ 2 ) .Ev e ni ft h eg r a phi ss p ar s e ( c o nt a i n sl e s snu mb mb ero fe dg es ) ,i tc o ns u me me s t h es a mes me pa c e.Ad di n gav er t e xi sO( V^ 2 )t i me .
Adj a ce nc yLi s t : Anar r ayofl i nk edl i s t si sus ed.Si z eoft hear r a yi sequal t onumberofv er t i c es .Lett hear r aybear r ay [ ] .Anent r y ar r ay [ i ]r epr es ent st hel i nk edl i s to fv er t i cesadj ac entt ot hei t hv er t e x.Thi sr epr e sent at i onc anal s obeus edt o r ep r e s entawei ght edgr aph.Thewei ght sofedgesc anbes t or edi nnodesofl i nk edl i s t s .Fol l owi ngi sadj ac enc y l i s tr epr es ent at i onoft heabov egr aph.
Ad j a ce nc yLi s tRe pr e s en t a t i o no ft h ea bo v eGr a ph Bel o wi sC c od ef oradj a cenc yl i s tr ep r e s ent at i onofa nundi r e ct edgr aph:
3
// A C Program to demonstrate adjacency list representation of graphs #include
#include // A structure to represent an adjacency list node struct AdjListNode int dest! struct AdjListNode" net! $! // A structure to represent an adjacency liat struct AdjList struct AdjListNode "head! // pointer to head node of list $! // A structure to represent a graph. A graph is an array of adjacency lists. // %i&e of array 'ill be ( )number of *ertices in graph+ struct ,raph int (! struct AdjList" array! $! // A utility function to create a ne' adjacency list node struct AdjListNode" ne'AdjListNode)int dest+ struct AdjListNode" ne'Node )struct AdjListNode"+ malloc)si&eof)struct AdjListNode++! ne'Node>dest - dest! ne'Node>net - NLL! return ne'Node! $ // A utility function that creates a graph of ( *ertices struct ,raph" create,raph)int (+ struct ,raph" graph - )struct ,raph"+ malloc)si&eof)struct ,raph++! graph>( - (! // Create an array of adjacency lists. %i&e of array 'ill be ( graph>array - )struct AdjList"+ malloc)( " si&eof)struct AdjList++! // 0nitiali&e each adjacency list as empty by ma1ing head as NLL int i! for )i - 2! i < (! 33i+ graph>array4i5.head - NLL! return graph! $ // Adds an edge to an undirected graph *oid add6dge)struct ,raph" graph7 int src7 int dest+ // Add an edge edge from src to dest. A ne' node is added to the adjacency // list of src. 8he node is added at the begining struct AdjListNode" ne'Node - ne'AdjListNode)dest+! ne'Node>net - graph>array4src5.head! graph>array4src5.head - ne'Node!
4
// %ince graph is undirected7 add an edge from dest to src also ne'Node - ne'AdjListNode)src+! ne'Node>net - graph>array4dest5.head! graph>array4dest5.head - ne'Node! $ // A utility function to print the adjacenncy list representation of graph *oid print,raph)struct ,raph" graph+ int *! for )* - 2! * < graph>(! 33*+ struct AdjListNode" pCra'l - graph>array4*5.head! printf)9:n Adjacency list of *erte ;d:n head 97 *+! 'hile )pCra'l+ printf)9> ;d97 pCra'l>dest+! pCra'l - pCra'l>net! $ printf)9:n9+! $ $ // ri*er program to test abo*e functions int main)+ // create the graph gi*en in abo*e fugure int ( - =! struct ,raph" graph - create,raph)(+! add6dge)graph7 27 +! add6dge)graph7 27 ?+! add6dge)graph7 7 @+! add6dge)graph7 7 +! add6dge)graph7 7 ?+! add6dge)graph7 @7 +! add6dge)graph7 7 ?+! // print the adjacency list representation of the abo*e graph print,raph)graph+! return 2! $
Ou t p ut :
Adjacency list of *erte 2 head > ?>
Adjacency list of *erte head > ?> > @> 2
Adjacency list of *erte @ head > >
5
Adjacency list of *erte head > ?> @>
Adjacency list of *erte ? head > > > 2 Pr o s : Sa v ess pa c eO( | V| +| E| ).I nt h ewo r s t c a se ,t h er eca nb eC( V,2 )n umb ero fe dg esi nag r a pht h us c o ns umi n gO( V^ 2 )s p ac e.Ad di n gav er t e xi se as i e r . Cons : Qu er i e sl i k ewh et h ert h er ei saned gef r o mv e r t e xut ov er t e xvar eno te ffic i e nta ndca nb ed on eO( V) .
Transitive closure of a graph December4,2012
Gi v enadi r ec t edgr aph,fi ndouti fav er t exj i sr eac habl ef r om anot herv er t e xi f oral l v er t e xpai r s( i ,j )i nt he gi v engr aph.Her er eac habl emeant hatt her ei sapat hf r om v er t e xit oj .Ther eac habi l i t ymat r i xi scal l ed t r ans i t i v ec l os ur eofagr aph. Thegr aphi sgi v eni nt hef or m ofadj ac enc ymat r i xsa y‘ gr aph[ V] [ V] ‘wher egr aph[ i ] [ j ]i s1i ft her ei sanedge f r om v er t exit ov er t exj ori i sequalt oj ,ot her wi s egr aph[ i ] [ j ]i s0. Fl oy dWar s hal l Al gor i t hm c anbeus ed,wec anc al c ul at et hedi s t anc emat r i xdi s t [ V] [ V]us i n gFl o y dWa r s h al l ,i f di s t [ i ] [ j ]i si nfi ni t e,t henj i snotr eac habl ef r om i ,ot her wi s ej i sr eachabl eandv al ueofdi s t [ i ] [ j ]wi l lbel esst hanV. I ns t eadofdi r ec t l yus i ngFl o ydWar s hal l ,wec anopt i mi z ei ti nt er msofs pac eandt i me,f ort hi spar t i c ul ar pr obl em.Fol l o wi nga r et heop t i mi z at i on s: 1) I ns t eadofi nt egerr es ul t antmat r i x( di s t [ V] [ V]i nfloy dwar s hal l ) ,wecanc r eat eabool eanr e ac habi l i t ymat r i x r eac h[ V] [ V]( wes av es pac e) .Thev al uer eac h[ i ] [ j ]wi l l be1i fj i sr e ac habl ef r om i ,ot her wi s e0. 2) I ns t eadofus i ngar i t hmet i coper at i ons ,wecanus el ogi c al oper at i ons .Forar i t hmet i coper at i on‘ +’ ,l ogi c al and ‘ &&’ i sus ed,andf ormi n,l ogi c al or‘ | | ’ i sus ed.( Wes av et i mebyac ons t antf ac t or .Ti mec ompl e xi t yi ssame t h ou g h) // Program for transiti*e closure using Bloyd arshall Algorithm #include
6
// Number of *ertices in the graph #define ( ? // A function to print the solution matri *oid print%olution)int reach454(5+! // Prints transiti*e closure of graph4545 using Bloyd arshall algorithm *oid transiti*eClosure)intgraph454(5+ /" reach4545 'ill be the output matri that 'ill finally ha*e the shortest distances bet'een e*ery pair of *ertices "/ int reach4(54(57 i7 j7 1! /" 0nitiali&e the solution matri same as input graph matri. Dr 'e can say the initial *alues of shortest distances are based on shortest paths considering no intermediate *erte. "/ for )i - 2! i < (! i33+ for )j - 2! j < (! j33+ reach4i54j5 - graph4i54j5! /" Add all *ertices one by one to the set of intermediate *ertices. > Eefore start of a iteration7 'e ha*e reachability *alues for all pairs of *ertices such that the reachability *alues consider only the *ertices in set 27 7 @7 .. 1$ as intermediate *ertices. > After the end of a iteration7 *erte no. 1 is added to the set of intermediate *ertices and the set becomes 27 7 @7 .. 1$ "/ for )1 - 2! 1 < (! 133+ // Pic1 all *ertices as source one by one for )i - 2! i < (! i33+ // Pic1 all *ertices as destination for the // abo*e pic1ed source for )j - 2! j < (! j33+ // 0f *erte 1 is on a path from i to j7 // then ma1e sure that the *alue of reach4i54j5 is reach4i54j5 - reach4i54j5 FF )reach4i5415 GG reach4154j5+! $ $ $ // Print the shortest distance matri print%olution)reach+! $ /" A utility function to print solution "/ *oid print%olution)int reach454(5+ printf )9Bollo'ing matri is transiti*e closure of the gi*en graph:n9+! for )int i - 2! i < (! i33+ for )int j - 2! j < (! j33+ printf )9;d 97 reach4i54j5+! printf)9:n9+! $ $ // dri*er program to test abo*e function int main)+
7
/" Let us create the follo'ing 'eighted graph 2 )2+>)+ F /F: = F F F F :F/ F )+>)@+ "/ int graph4(54(5 - 7 7 27 $7 27 7 7 2$7 27 27 7 $7 27 27 27 $ $! // Print the solution transiti*eClosure)graph+! return 2! $
Out put :
Bollo'ing matri is transiti*e closure of the gi*en graph 2 2 2 2 2 2 Ti meCo mp l e x i t y :O( V^ 3 )wh er eVi sn umb ero fv e r t i c e si nt h eg i v e ng r a ph .
Dynamic Programming | Set 23 (Bellman–ord !lgorithm" December1,2012
Gi v e nagr a phan das ou r c ev er t e xs r ci ngr aph,fi nds hor t es tpat hsf r oms r ct oal l v er t i cesi nt hegi v engr aph. Th eg r a phma yc o nt a i nne ga t i v ewe i g hte dg es . Wehavedi scuss edDi j k s t r a ’ sal gor i t hm f ort hi spr obl em.Di j k s r a ’ sal gor i t hm i saGr eedyal gor i t hm andt i me c ompl e xi t yi sO( VLogV)( wi t ht heus eofFi bona cc ihea p) . Di j k s t r adoes n’ twor kf orGr aphswi t hnegat i v ewei ght edg es ,Bel l manFor dwo r k sf ors uc hgr aph s.Bel l manFor di sal s os i mpl ert hanDi j k s t r aands ui t eswel l f or di s t r i but eds y s t ems .Butt i mec ompl e xi t yofBel l manFor di sO( BE) ,whi c hi smor et hanDi j k s t r a. Al gor i t hm Fol l owi ngar et hedet ai l eds t eps .
8
I nput : Gr a phan das ou r c ev e r t e xsr c Ou t p ut : Shor t es tdi s t anc et oal l v er t i c esf r oms r c .I ft her ei sanegat i v ewei ghtc yc l e,t hens hor t es tdi s t anc esar e notc al c ul at ed,negat i v ewei ghtc y cl ei sr epor t ed. 1) Thi sst epi ni t i al i z esdi s t anc esf r om s our c et oal l v er t i c esasi nfi ni t eanddi s t anc et os our c ei t s el fas0.Cr eat e anar r aydi s t [ ]ofs i z e| V|wi t hal l v al uesasi nfi ni t ee xc eptdi s t [ s r c ]wher es r ci ssour c ev er t ex . 2) Thi sst epc al c ul at esshor t es tdi s t anc es .Dof ol l owi ng| V| 1t i meswher e| V|i st henumberofv er t i c esi ngi v en g r a p h . …. . a) Dof o l l o wi n gf o re ac he dg eu v ………………I fd i s t [ v ]>d i s t [ u ]+we i g hto fe dg eu v ,t h enup da t edi s t [ v ] …………………. di st [ v]=di st [ u]+wei ghtofedgeuv 3) Thi sst epr epor t si ft her ei sanegat i v ewei ghtc y cl ei ngr aph.Dof ol l owi ngf oreac hedgeuv ……I fd i s t [ v ]>d i s t [ u]+wei ghtofedgeuv ,t hen“ Gr aphc ont ai nsneg at i v ewei ghtc y c l e” Thei deaofs t ep3i s ,s t ep2guar ant eess hor t es tdi s t anc esi fgr aphdoes n’ tc ont ai nnegat i v ewei ghtc y cl e.I fwe i t er at et hr oughal l edgesonemo r et i meandgetas hor t erp at hf oran yv er t e x,t hent her ei san eg at i v ewei ght c ycl e Li k eo t h erDy n ami cPr o gr a mmi n gPr o bl e ms ,t h ea l g or i t h mc al c ul a t es h or t e s tp at h si n How doest hi swor k? bo t t omupma nner .I tfi r s tc al c ul at est hes hor t es tdi s t anc esf ort hes hor t es tpat hswhi c hha v eat mos ton ee dge i nt hepat h.Then,i tc al c ul at esshor t es tpat hswi t hat nos t2edges ,ands oon.Af t ert hei t hi t er at i onofout er l o op ,t h es ho r t e s tp at h swi t hatmo s ti e dg esar ec al c ul a t e d.Th er eca nb ema x i mu m| V|–1e dg esi nan y s i mpl epat h,t hati swh yt heout erl oopr uns| v |–1t i mes .Thei deai s ,i fwehav ec al c ul at eds hor t es tpat hswi t h atmos ti edges ,t hena ni t er at i ono v eral l edg esguar ant eest ogi v es hor t es tpat hwi t hat mos t( i +1)edge s ( Pr oofi ssi mpl e,y ouc anr ef er t hi sorMI TVi d eoLe c t u r e ) Exampl e L etu su nd er s t a ndt h ea l g or i t h m wi t hf o l l o wi n ge x amp l eg r a ph .Th ei ma ge sa r et a k enf r o mt hi ss o u r c e . Lett hegi v ens our c ev er t exbe0.I ni t i al i z eal l di s t anc esasi nfi ni t e,ex ceptt hedi s t anc et os our c ei t s el f .T ot al numbe ro fv er t i c esi nt hegr aphi s5,s oa l l e dg esmu s tb ep r o c es s e d4t i me s .
9
Letal l edgesar epr oc es sedi nf ol l owi ngor der :( B, E) ,( D, B) ,( B, D) ,( A, B) ,( A, C) ,( D, C) ,( B, C) ,( E, D) .Weget f ol l o wi ngdi s t anc eswhenal l edgesar epr oc es s edfi r s tt i me.Thefi r s tr o wi ns howsi ni t i al di s t anc es .Thes ec ond r o ws h owsd i s t a nc e swh ened ge s( B, E) ,( D, B) ,( B, D)a nd( A, B)a r epr o ce ss ed .Th et h i r dr o ws ho wsd i s t a nc es wh en( A, C)i sp r o c es s e d.Th ef o ur t hr o ws h owswh en( D, C) ,( B, C)a nd( E, D)a r epr o c es s e d.
Thefi r s ti t er at i onguar ant eest ogi v eal ls hor t es tpat hswhi c ha r eatmos t1edgel ong.Wegetf ol l o wi ng d i s t a nc eswh enal l e dg esa r epr o ce ss e ds ec o ndt i me( Th el a str o ws ho wsfi n al v a l u es ) .
These condi t er a t i ong uar ant eest og i v eal l s hor t es tpat h swhi c har eatmos t2e dgesl ong.Theal gor i t hm pr oc es s esal l edge s2mor et i mes .Thedi s t anc esar emi ni mi z edaf t ert hes ec ondi t er at i on,s ot hi r dandf our t h i t er at i onsdon’ tupdat et hedi s t anc es . I mpl ement at i on: // A C / C33 program for EellmanBordHs single source shortest path algorithm. #include #include
10
#include #include // a structure to represent a 'eighted edge in graph struct 6dge int src7 dest7 'eight! $! // a structure to represent a connected7 directed and 'eighted graph struct ,raph // (> Number of *ertices7 6> Number of edges int (7 6! // graph is represented as an array of edges. struct 6dge" edge! $! // Creates a graph 'ith ( *ertices and 6 edges struct ,raph" create,raph)int (7 int 6+ struct ,raph" graph - )struct ,raph"+ malloc) si&eof)struct ,raph+ +! graph>( - (! graph>6 - 6! graph>edge - )struct 6dge"+ malloc) graph>6 " si&eof) struct 6dge + +! return graph! $ // A utility function used to print the solution *oid printArr)int dist457 int n+ printf)9(erte istance from %ource:n9+! for )int i - 2! i < n! 33i+ printf)9;d :t:t ;d:n97 i7 dist4i5+! $ // 8he main function that finds shortest distances from src to all other // *ertices using EellmanBord algorithm. 8he function also detects negati*e // 'eight cycle *oid EellmanBord)struct ,raph" graph7 int src+ int ( - graph>(! int 6 - graph>6! int dist4(5! // %tep I 0nitiali&e distances from src to all other *ertices as 0NB0N086 for )int i - 2! i < (! i33+ dist4i5 - 0N8JKA! dist4src5 - 2! // %tep @I Mela all edges F(F times. A simple shortest path from src // to any other *erte can ha*e atmost F(F edges for )int i - ! i <- (! i33+ for )int j - 2! j < 6! j33+ int u - graph>edge4j5.src! int * - graph>edge4j5.dest!
11
int 'eight - graph>edge4j5.'eight! if )dist4u5 3 'eight < dist4*5+ dist4*5 - dist4u5 3 'eight! $ $ // %tep I chec1 for negati*e'eight cycles. 8he abo*e step guarantees // shortest distances if graph doesnHt contain negati*e 'eight cycle. // 0f 'e get a shorter path7 then there is a cycle. for )int i - 2! i < 6! i33+ int u - graph>edge4i5.src! int * - graph>edge4i5.dest! int 'eight - graph>edge4i5.'eight! if )dist4u5 3 'eight < dist4*5+ printf)9,raph contains negati*e 'eight cycle9+! $ printArr)dist7 (+! return! $ // ri*er program to test abo*e functions int main)+ /" Let us create the graph gi*en in abo*e eample "/ int ( - =! // Number of *ertices in graph int 6 - ! // Number of edges in graph struct ,raph" graph - create,raph)(7 6+! // add edge 2 )or AE in abo*e figure+ graph>edge425.src - 2! graph>edge425.dest - ! graph>edge425.'eight - ! // add edge 2@ )or AC in abo*e figure+ graph>edge45.src - 2! graph>edge45.dest - @! graph>edge45.'eight - ?! // add edge @ )or EC in abo*e figure+ graph>[email protected] - ! graph>[email protected] - @! graph>edge4@5.'eight - ! // add edge )or E in abo*e figure+ graph>edge45.src - ! graph>edge45.dest - ! graph>edge45.'eight - @! // add edge ? )or A6 in abo*e figure+ graph>edge4?5.src - ! graph>edge4?5.dest - ?! graph>edge4?5.'eight - @! // add edge @ )or C in abo*e figure+ graph>edge4=5.src - ! graph>edge4=5.dest - @! graph>edge4=5.'eight - =!
12
// add edge )or E in abo*e figure+ graph>edge4O5.src - ! graph>edge4O5.dest - ! graph>edge4O5.'eight - ! // add edge ? )or 6 in abo*e figure+ graph>edge45.src - ?! graph>edge45.dest - ! graph>edge45.'eight - ! EellmanBord)graph7 2+! return 2! $
Out put :
(erte
istance from %ource
2
2
@
@
@
?
Not es 1)Negat i v ewe i g ht sa r ef oundi nv ar i ou sappl i c at i onsofgr aph s.Fore x ampl e,i ns t eadofpa yi ngc os tf orapat h, wema yg ets o mead v an t a gei fwef o l l o wt h ep at h . 2) Bel l manFor dwor k sbet t er( bet t ert hanDi j k s r a ’ s )f ordi s t r i but eds y st ems .Unl i k eDi j k sr a ’ swher eweneedt o fi n dmi n i mu mv a l u eo fa l l v e r t i c es ,i nBe l l ma nFo r d ,e dg esar ec on si d er e do nebyon e.
Greedy !lgorithms | Set # (Di$%stra&s shortest path algorithm" November25,2012
Gi v enagr aphandas our c ev er t e xi ngr ap h,fi ndshor t es tpat hsf r om s our c et oal l v er t i c esi nt heg i v engr aph. Di j k st r a’ sal gor i t hm i sv er ysi mi l art oPr i m’ sal g or i t h mf o rmi n i mu ms pa nn i n gt r e e .L i k ePr i m’ sMST ,wege ne r a t e a SPT( s hor t es tpat ht r ee) wi t hg i v ens our c easr oo t .Wemai nt ai nt wos et s ,ones etc ont ai nsv er t i c esi n cl uded i ns hor t es tpat ht r ee,ot hers eti nc l udesver t i c esnoty eti nc l udedi ns hor t es tpat ht r ee.Atev er yst epoft he
13
al gor i t hm,wefin daver t e xwhi c hi si nt heo t hers et( s etofno ty eti nc l u ded)andha smi ni mum di s t anc ef r om s o u r c e . Bel owar et hedet ai l edst epsus edi nDi j k st r a ’ sal gor i t hm t ofi ndt heshor t es tpat hf r om as i ngl esour c ev er t e xt o al lot herv er t i c esi nt hegi v engr aph. Al gor i t hm Cr e at eas e ts p t Se t ( s hor t es tp at ht r ees et )t hatk eepst r ac kofv er t i c esi nc l udedi ns hor t es tp at ht r ee,i . e. , 1) whos emi ni mum di s t anc ef r om s our c ei sc al c ul at edandfinal i z ed.I ni t i al l y ,t hi ss eti sempt y . 2) As si gnadi s t anc ev al uet oal l v er t i c esi nt hei nputgr aph.I ni t i al i z eal l di s t anc ev al uesasI NFI NI TE.As si gn di s t anc ev al ueas0f ort hes our c ev er t e xs ot hati ti spi c k edfi r s t . 3) Wh i l es p t Se t does n’ ti nc l udeal l v er t i c es …. a) Pi c kav er t e xuwhi c hi snott her ei ns p t Se t a ndh asmi n i mu md i s t a nc ev a l u e. …. b) I nc l udeut os p t Se t . …. c) Updat edi s t anc ev al ueofal l adj ac entv er t i c esofu.T oupdat et hedi s t anc ev al ues ,i t er at et hr oughal l adj ac entv er t i c es .Fore ver yadj ac entv er t e xv ,i fs um ofdi s t an cev al ueofu( f r om s our c e)andwei g htofedgeuv ,i sl es st hant hedi s t anc ev al ueofv ,t henupdat et hedi s t anc ev al ueofv . L etu su nd er s t a ndwi t ht h ef o l l o wi n ge x amp l e :
Th es e ts p t Se t i si ni t i al l yempt yanddi s t anc esas si gnedt ov er t i c esar e{ 0,I NF ,I NF ,I NF ,I NF ,I NF ,I NF ,I NF} whe r eI NFi ndi c at esi n fini t e.No w pi c kt hev er t e xwi t hmi ni mum di s t anc ev al ue.Thev er t e x0i spi c k ed,i nc l udei t i ns p t Se t .Sos pt Se tb ec ome s{ 0} .Af t eri n cl udi ng0t os p t Se t ,updat edi s t anc ev al uesofi t sadj ac entv er t i c es . Ad j a ce ntv e r t i c esof0ar e1a nd7.Th ed i s t a nc ev al u esof1an d7ar eup da t e da s4a nd8.Fo l l o wi n gs ub gr a ph s howsv er t i c esandt hei rdi s t anc ev al ues ,onl yt hever t i c eswi t hfini t edi s t anc ev al uesar eshown.Thever t i c es i n cl u de di nSPTa r esh owni ngr e enc ol o r .
14
Pi c kt h ev e r t e xwi t hmi n i mu md i s t a nc ev a l u ea ndn ota l r e ad yi n c l u de di nSPT( n oti ns pt SET) .Th ev e r t e x1i s p i c k eda nda dd edt os pt Se t .Sos p t Se tn owb ec ome s{ 0 ,1 } .Up dat et h ed i s t a nc ev a l u esofa dj a ce ntv e r t i c esof 1 .Th ed i s t a nc ev a l u eo fv e r t e x2b ec o me s12 .
Pi c kt h ev er t e xwi t hmi ni mum di s t anc ev al ueandno tal r eadyi n cl udedi nSPT( noti nsp t SET) .Ver t e x7i s pi c k ed.Sospt Setno wb ec ome s{ 0,1,7 } . Updat et hedi s t anc ev al uesofadj a centv er t i c esof7.Thedi s t anc e v a l u eo fv e r t e x6a nd8b ec ome sfi ni t e( 1 5a nd9r e sp ec t i v e l y ) .
Pi c kt h ev er t e xwi t hmi ni mum di s t anc ev al ueandno tal r eadyi n cl udedi nSPT( noti nsp t SET) .Ver t e x6i s pi c k ed.Sospt Setno wb ec ome s{ 0,1,7,6} .Updat et hedi s t anc ev al u esofadj a centv er t i c esof6.Thedi s t an ce v a l u eo fv e r t e x5a nd8a r eup dat e d.
15
Wer e pe att h ea bo v es t e psun t i l s pt Se tdoes n’ ti nc l udeal l v er t i c esofgi v engr aph.Fi nal l y ,wegett hef ol l owi ng Sh or t e s tPa t hT r e e( SPT) .
How t oi mpl ementt heaboveal gor i t hm? Weus eabool eanar r a ys pt Set [ ]t or epr es entt hes etofv er t i c esi nc l udedi nSPT .I fav al ues pt Set [ v ]i st r ue, t henv er t exvi si nc l udedi nSPT ,ot her wi s enot .Ar r a ydi s t [ ]i sus edt os t or es hor t es tdi s t anc ev al uesofal l v er t i ces . // A C / C33 program for ij1straHs single source shortest path algorithm. // 8he program is for adjacency matri representation of the graph #include #include // Number of *ertices in the graph #define ( Q // A utility function to find the *erte 'ith minimum distance *alue7 from // the set of *ertices not yet included in shortest path tree int ministance)int dist457 bool spt%et45+ // 0nitiali&e min *alue int min - 0N8JKA7 minJinde! for )int * - 2! * < (! *33+ if )spt%et4*5 -- false GG dist4*5 <- min+ min - dist4*57 minJinde - *! return minJinde! $ // A utility function to print the constructed distance array int print%olution)int dist457 int n+ printf)9(erte istance from %ource:n9+! for )int i - 2! i < (! i33+ printf)9;d :t:t ;d:n97 i7 dist4i5+! $ // Buntion that implements ij1straHs single source shortest path algorithm // for a graph represented using adjacency matri representation *oid dij1stra)int graph4(54(57 int src+ int dist4(5! // 8he output array. dist4i5 'ill hold the shortest // distance from src to i
16
bool spt%et4(5! // spt%et4i5 'ill true if *erte i is included in shortest // path tree or shortest distance from src to i is finali&ed // 0nitiali&e all distances as 0NB0N086 and stp%et45 as false for )int i - 2! i < (! i33+ dist4i5 - 0N8JKA7 spt%et4i5 - false! // istance of source *erte from itself is al'ays 2 dist4src5 - 2! // Bind shortest path for all *ertices for )int count - 2! count < (! count33+ // Pic1 the minimum distance *erte from the set of *ertices not // yet processed. u is al'ays eRual to src in first iteration. int u - ministance)dist7 spt%et+! // Kar1 the pic1ed *erte as processed spt%et4u5 - true! // pdate dist *alue of the adjacent *ertices of the pic1ed *erte. for )int * - 2! * < (! *33+ // pdate dist4*5 only if is not in spt%et7 there is an edge from // u to *7 and total 'eight of path from src to * through u is // smaller than current *alue of dist4*5 if )Sspt%et4*5 GG graph4u54*5 GG dist4u5 S- 0N8JKA GG dist4u53graph4u54*5 < dist4*5+ dist4*5 - dist4u5 3 graph4u54*5! $ // print the constructed distance array print%olution)dist7 (+! $ // dri*er program to test abo*e function int main)+ /" Let us create the eample graph discussed abo*e "/ int graph4(54(5 - 27 ?7 27 27 27 27 27 7 2$7 27 27 7 27 27 27 27 7 2$7 27 7 27 7 27 ?7 27 27 @$7 27 27 7 27 Q7 ?7 27 27 2$7 27 27 27 Q7 27 27 27 27 2$7 27 27 ?7 27 27 27 @7 27 2$7 27 27 27 ?7 27 @7 27 7 O$7 7 7 27 27 27 27 7 27 $7 27 27 @7 27 27 27 O7 7 2$ $! dij1stra)graph7 2+! return 2! $
Ou t p ut :
(erte
istance from %ource
17
2
2
?
@
@
Q
?
@
=
O
Q
?
Not es: 1) Thec od ec al c ul at ess hor t es tdi s t anc e,b utdoes n’ tc al c ul at et hep at hi nf or mat i on.Wec anc r eat eapar ent ar r a y ,updat et hep ar entar r a ywhe ndi s t an cei supdat ed( l i k epr i m’ si mpl ement at i on )a ndus ei ts h owt h e s hor t es tpat hf r om s our c et odi ffer entv er t i c es . 2) Thec od ei sf orundi r ec t edgr a ph,s amedi j ek s t r af unc t i onc anbeus edf ordi r ec t edgr ap hsal s o. 3) Thec odefi ndsshor t es tdi s t anc esf r om s our c et oal l v er t i c es .I fwear ei nt er es t edonl yi ns hor t es tdi s t anc e f r o ms o ur c et oas i n gl et a r g et ,wec anb r e akt h ef o rl o opwh ent h ep i c k edmi n i mu md i s t a nc ev e r t e xi seq ua lt o t ar get( St ep3. aofal gor i t hm) . 4) Ti meCompl e xi t yoft hei mpl ement at i oni sO( V^ 2) .I ft hei nput gr a phi sr epr e sent edu si ngadj a cen cyl i s t ,i t c a nb er e du ce dt oO( El o gV)wi t ht h eh el pofb i n ar yh ea p.Wewi l ls o onbedi s c us s i n gO( EL ogV)a l g or i t h ma s as e pa r a t ep os t . 5) Di j k s t r a ’ sal go r i t hm d oes n’ twor kf orgr aph swi t hneg at i v ewei ghtedge s.Forgr aph swi t hn eg at i v ewei ght e dg es ,Bel l man–Fo r dal gor i t hm c anb eu s ed ,wewi l l s o onb ed i s c us s i n gi ta sas e pa r at ep os t . Pl eas ewr i t ecomment si fy oufindan yt hi ngi n cor r ec t ,o ry o uwantt oshar emo r ei nf or mat i onabo utt het opi c d i s c u s s e da bo v e .
Greedy !lgorithms | Set ' (Prim&s inimum Spanning Tree (ST"" November18,2012
18
Wehavedi scuss edKr u s ka l ’ sal g or i t h mf o rMi n i mu m Sp an ni n gT r e e . L i k eKr us kal ’ sal gor i t hm,Pr i m’ sal gor i t hm i sal soaGr eedyal gor i t hm. I ts t ar t swi t hanempt yspanni ngt r ee.Thei deai st omai nt ai nt wos et sofv er t i c es . Thefi r s ts etc ont ai nst hev er t i c esal r eadyi nc l udedi nt heMST ,t heot hers etc ont ai nst hev er t i c esnoty et i nc l u ded.Ate v er ys t ep,i tc ons i der sal l t heedge st ha tc onne ctt het wos et s ,a ndp i c k st hemi ni mum wei gh t edgef r om t hes eedge s.Af t erpi c k i ngt h eedge,i tmo v est heo t herendpoi ntoft heedget ot hese tc ont ai ni ng MST . Agr oupofe dgest hatc onnec t st wos etofv er t i c esi nagr aphi sc al l ed c uti ngr apht heor y .So,ate ver ys t epof Pr i m’ sal gor i t hm,wefi ndac ut( oft wos et s ,o nec ont ai nst hev er t i c esal r e adyi nc l udedi nMSTan do t her c ont ai nsr es toft hev er i c es ) ,p i c kt hemi ni mum wei ghte dg ef r om t hec uta ndi nc l udet hi sv er t e xt oMSTSe t( t he s ett hatc ont ai nsal r eadyi nc l udedv er t i c es ) . How doesPr i m’ sAl gor i t hm Wor k? Th ei deabe hi ndPr i m’ sal g or i t hm i ss i mpl e,aspan ni ngt r eemea nsal l v er t i c esmus tb ec onne ct ed.Sot het wodi s j oi nts ubs et s( d i s c us s edab ov e)ofv er t i c esmus tbec onnec t edt o mak eaSpanni ngT r e e.An dt h eymu s tb ec o nn ec t e dwi t ht h emi n i mu m we i g hte dg et oma k ei t aMi ni mumSp an n i n gT r e e. Al gor i t hm 1) Cr e at eas e tms t Set t hatk eep st r ac kofv er t i c esal r e adyi nc l u dedi nMST . 2) As si gnak eyval uet oal l v er t i c esi nt hei nputgr aph.I ni t i al i z eal l k eyval uesasI NFI NI TE.As si gnk eyval ueas 0f ort hefi r s tv er t exsot hati ti spi c kedfir s t . 3) Whi l ems t Setdoes n’ ti nc l udeal l v er t i c es …. a) Pi c kav er t e xu whi c hi snott her ei nms t Se tandhasmi ni mum keyval ue. …. b) I nc l udeut oms t Se t . …. c) Updat ek eyv al ueofal l adj ac entv er t i c esof u.T oupdat et hek eyval ues ,i t er at et hr oughal l adj ac ent v er t i c es .Forev er yadj ac entv er t e xv ,i fwei ghtofedgeuv i sl es st hant hepr ev i ousk eyv al ueof v ,upd at et he k e yv a l u ea swe i g hto fuv Th ei d eaofu si n gk e yv al u esi st opi c kt h emi n i mu m we i g hte dg ef r o mcut .Th ek e yv a l u esar eu s edo nl yf o r v er t i c eswhi c har eno ty e ti nc l udedi nMST ,t hek e yv al u ef ort hes ev er t i c esi ndi c at et hemi ni mum wei g htedge s c onnec t i ngt hem t ot hes etofv er t i c esi nc l ude di nMST .
19
L etu su nd er s t a ndwi t ht h ef o l l o wi n ge x amp l e :
Th es e tms t Se ti si ni t i al l yempt yandk ey sas si gnedt ov er t i c esar e{ 0,I NF ,I NF ,I NF ,I NF ,I NF ,I NF ,I NF}wher e I NFi ndi c at esi nfi ni t e.Nowpi c kt hever t e xwi t hmi ni mum k eyv al ue.Thev er t e x0i spi c k ed,i nc l udei ti n mst Set . Soms t Se tbec omes{ 0} .Af t eri nc l udi ngt omst Set ,updat ek eyv al uesofadj ac entv er t i c es .Adj ac entv er t i c esof 0a r e1a nd7.Th ek e yv a l u esof1a nd7ar eu pd at e da s4an d8 .Fo l l o wi n gs u bg r a phs h owsv e r t i c e sa ndt h ei r k e yv al ues ,onl yt hev er t i c eswi t hfini t ek eyv al uesar esho wn.Thever t i c esi nc l udedi nMSTa r es ho wni ngr een c ol or .
Pi c kt h ev e r t e xwi t hmi n i mu mk e yv al u ea ndno ta l r e ad yi n c l u de di nMST( n oti nms t SET) .Th ev e r t e x1i s p i c k edan da dd edt oms t Se t .Soms t Se tn owb ec ome s{ 0 ,1 } .Up da t et h ek e yv al u eso fa dj a c en tv e r t i c eso f1 . Th ek e yv a l u eo fv e r t e x2b e c ome s8 .
Pi c kt h ev e r t e xwi t hmi n i mu mk e yv al u ea ndno ta l r e ad yi n c l u de di nMST( n oti nms t SET) .Wec anei t h erp i c k v er t e x7orv er t e x2,l e tv er t e x7i spi c k ed.Soms t Se tn owbec omes{ 0,1,7} .Up dat et heke yv al uesofa dj ac ent
20
v er t i c esof7.Theke yv al ueofv er t e x6and8b ec omesfi ni t e( 7and1r es pe ct i v el y ) .
Pi c kt h ev e r t e xwi t hmi n i mu mk e yv a l u ea ndn ota l r e ad yi n c l u de di nMST( n oti nms t SET) .Ver t e x6i spi c k ed . Soms t Se tn owb ec ome s{ 0 ,1 ,7 ,6 } .Up da t et h ek e yv al u esofa dj a c en tv e r t i c e so f6 .Th ek e yv al u eo fv e r t e x5 a nd8ar eu pd at e d.
Wer e pe att h ea bo v es t e psun t i l ms t Se tdoes n’ ti nc l udeal lv er t i c esofgi v engr aph.Fi nal l y ,wegett hef ol l owi ng g r a p h .
How t oi mpl ementt heaboveal gor i t hm? Weus eabool eanar r a yms t Set [ ]t or epr es entt hes etofv er t i c esi nc l udedi nMST .I faval uems t Set [ v ]i st r ue, t henv er t e xvi si nc l udedi nMST ,ot her wi s enot .Ar r a yk ey [ ]i sus edt os t or ek eyval uesofal l v er t i c es .Anot her ar r a ypar ent [ ]t os t or ei nde x esofpa r e ntn odesi nMST .Thep ar entar r a yi st heout puta r r a ywhi c hi sus edt o s h o wt h ec on s t r u c t e dMST . // A C / C33 program for PrimHs Kinimum %panning 8ree )K%8+ algorithm. // 8he program is for adjacency matri representation of the graph #include #include
21
// Number of *ertices in the graph #define ( = // A utility function to find the *erte 'ith minimum 1ey *alue7 from // the set of *ertices not yet included in K%8 int minTey)int 1ey457 bool mst%et45+ // 0nitiali&e min *alue int min - 0N8JKA7 minJinde! for )int * - 2! * < (! *33+ if )mst%et4*5 -- false GG 1ey4*5 < min+ min - 1ey4*57 minJinde - *! return minJinde! $ // A utility function to print the constructed K%8 stored in parent45 int printK%8)int parent457 int n7 int graph4(54(5+ printf)96dge eight:n9+! for )int i - ! i < (! i33+ printf)9;d ;d ;d :n97 parent4i57 i7 graph4i54parent4i55+! $ // Bunction to construct and print K%8 for a graph represented using adjacency // matri representation *oid primK%8)int graph4(54(5+ int parent4(5! // Array to store constructed K%8 int 1ey4(5! // Tey *alues used to pic1 minimum 'eight edge in cut bool mst%et4(5! // 8o represent set of *ertices not yet included in K%8 // 0nitiali&e all 1eys as 0NB0N086 for )int i - 2! i < (! i33+ 1ey4i5 - 0N8JKA7 mst%et4i5 - false! // Al'ays include first st *erte in K%8. 1ey425 - 2! // Ka1e 1ey 2 so that this *erte is pic1ed as first *erte parent425 - ! // Birst node is al'ays root of K%8 // 8he K%8 'ill ha*e ( *ertices for )int count - 2! count < (! count33+ // Pic1 thd minimum 1ey *erte from the set of *ertices // not yet included in K%8 int u - minTey)1ey7 mst%et+! // Add the pic1ed *erte to the K%8 %et mst%et4u5 - true! // pdate 1ey *alue and parent inde of the adjacent *ertices of // the pic1ed *erte. Consider only those *ertices 'hich are not yet // included in K%8 for )int * - 2! * < (! *33+ // graph4u54*5 is non &ero only for adjacent *ertices of m // mst%et4*5 is false for *ertices not yet included in K%8 // pdate the 1ey only if graph4u54*5 is smaller than 1ey4*5 if )graph4u54*5 GG mst%et4*5 -- false GG graph4u54*5 < 1ey4*5+
22
parent4*5
- u7 1ey4*5 - graph4u54*5!
$ // print the constructed K%8 printK%8)parent7 (7 graph+! $
// dri*er program to test abo*e function int main)+ /" Let us create the follo'ing graph @ )2+)+)@+ F / : F OF / := F F / : F )+)?+ Q "/ int graph4(54(5 - 27 @7 27 O7 2$7 @7 27 7 7 =$7 27 7 27 27 $7 O7 7 27 27 Q$7 27 =7 7 Q7 2$7 $! // Print the solution primK%8)graph+! return 2! $
Out put :
6dge
eight
2
@
@
2
O
?
=
Ti meCo mp l e x i t yoft h ea bo v ep r o gr a mi sO( V^ 2 ) .I ft h ei n pu t gr aphi sr ep r e s ent edus i nga dj ac enc yl i s t ,t hen t h et i mec omp l e x i t yofPr i m’ sal g or i t h mc anb er e du c edt oO( El o gV)wi t ht h eh el po fb i n ar yhe ap .Wewi l l s oo n b ed i s c u s s i n gO( EL ogV)a l g or i t h ma sas e pa r a t ep os t .
Greedy !lgorithms | Set 2 ()rus%al&s inimum Spanning Tree !lgorithm" Oc t o be r3 0,2 01 2
23
Whati sMi ni mum Spanni ngTr ee? Gi v e nac on ne c t e da ndun di r e c t e dg r a ph ,as panni n gt r ee oft hatgr a phi sas ubgr apht hati sat r e eand c onnec t sal l t hever t i c est oget her .As i n gl egr a phc anha v eman ydi ff er e nts panni ngt r ees .A mi ni mum spanni ng t r e e( MST) o rmi n i mu m we i g hts pa nn i n gt r e ef o rawe i g ht e d,c on ne ct e da ndun di r e ct e dg r a phi sas pa nn i n gt r e e wi t hwei ghtl es st hanorequal t ot hewei ghtofe v er yot hers panni ngt r ee.Thewei ghtofas pan ni ngt r eei st he s um o fwe i g ht sg i v e nt oea ched geoft h es pa nn i n gt r e e. Howmanyedgesdoesami ni mum spanni ngt r eehas? Ami n i mu ms p an ni n gt r e eh as( V–1 )e dg eswh er eVi st h en umb ero fv e r t i c e si nt h eg i v e ng r a ph . Wh ata r et h ea pp l i c a t i o nso fMi n i mu m Sp an ni n gT r e e? Seet hi sf orappl i c at i onsofMST . Bel o w ar et hes t epsf orfi ndi ngMSTus i n gKr u sk al ’ sal gor i t hm 1. %ort all the edges in nondecreasing order of their 'eight.
2. Pic1 the smallest edge. Chec1 if it forms a cycle 'ith the spanning
tree formed so far. 0f cycle is not formed7 include this edge. 6lse7 discard it.
3. Mepeat step#@ until there are )(+ edges in the spanning tree.
Thest ep#2usesUni onFi ndal gor i t hm t ode t e ctc y c l e .Sower e co mme ndt or e adf o l l o wi n gp os ta sa pr er equi s i t e. Un i o nFi n dAl g or i t h m |Se t1( De t e ctCy c l ei naGr a ph ) Un i o nFi n dAl g or i t h m |Se t2( Un i o nByRa nka ndPa t hCo mp r e s s i o n ) Th ea l g or i t h mi saGr e ed yAl g or i t h m.Th eGr e ed yCh oi c ei st op i c kt h es ma l l e stwe i g hte dg et h atd oe sn ot c a us eac y c l ei nt h eMSTc on s t r u ct e ds of a r .L etu su nd er s t a ndi twi t ha ne x amp l e :Co ns i d ert h eb el o wi n pu t gr aph.
24
Th eg r a phc o nt a i n s9v e r t i c e sa nd1 4e dg es .So ,t h emi n i mu ms p an ni n gt r e ef o r me dwi l l b eh a vi n g( 9–1 )=8 e dg es .
After sortingI eight
%rc
est
O
@
@
@
O
=
?
2
?
@
=
O
O
@
2
@
Q
?
2
=
?
?
=
No wp i c kal l e dg eson eb yon ef r o ms or t e dl i s to fe dg es c ke dg e76 : Noc y cl ei sf or med,i nc l udei t . 1.Pi
25
2.Pi c ke dg e82 : Noc y cl ei sf or med,i nc l udei t .
3.Pi c ke dg e65 : Noc y cl ei sf or med,i nc l udei t .
c ke dg e01 : Noc y cl ei sf or med,i nc l udei t . 4.Pi
c ke dg e25 : Noc y cl ei sf or med,i nc l udei t . 5.Pi
6. Pi c ked ge8 6 :Si nc ei nc l udi ngt hi sedger es ul t si nc yc l e,di s car di t . 7.Pi c ke dg e23 : Noc y cl ei sf or med,i nc l udei t .
26
8.Pi c ke dg e78 : Si nc ei nc l udi ngt hi sedger es ul t si nc yc l e,di s car di t . 9.Pi c ke dg e07 : Noc y cl ei sf or med,i nc l udei t .
10.Pi c ked ge12 :Si nc ei nc l udi ngt hi sedger es ul t si nc yc l e,di s car di t . 11.Pi c ke dg e34 : Noc y cl ei sf or med,i nc l udei t .
Si n cet h en umb ero fe dg esi n c l u de de qu al s( V–1) ,t h ea l g or i t h ms t o pshe r e . // Trus1alHs algortihm to find Kinimum %panning 8ree of a gi*en connected7 // undirected and 'eighted graph #include #include #include // a structure to represent a 'eighted edge in graph struct 6dge int src7 dest7 'eight! $! // a structure to represent a connected7 undirected and 'eighted graph struct ,raph // (> Number of *ertices7 6> Number of edges int (7 6! // graph is represented as an array of edges. %ince the graph is // undirected7 the edge from src to dest is also edge from dest // to src. Eoth are counted as edge here. struct 6dge" edge! $! // Creates a graph 'ith ( *ertices and 6 edges struct ,raph" create,raph)int (7 int 6+ struct ,raph" graph - )struct ,raph"+ malloc) si&eof)struct ,raph+ +!
27
graph>( - (! graph>6 - 6! graph>edge - )struct 6dge"+ malloc) graph>6 " si&eof) struct 6dge + +! return graph! $ // A structure to represent a subset for unionfind struct subset int parent! int ran1! $! // A utility function to find set of an element i // )uses path compression techniRue+ int find)struct subset subsets457 int i+ // find root and ma1e root as parent of i )path compression+ if )subsets4i5.parent S- i+ subsets4i5.parent - find)subsets7 subsets4i5.parent+! return subsets4i5.parent! $ // A function that does union of t'o sets of and y // )uses union by ran1+ *oid nion)struct subset subsets457 int 7 int y+ int root - find)subsets7 +! int yroot - find)subsets7 y+! // Attach smaller ran1 tree under root of high ran1 tree // )nion by Man1+ if )subsets4root5.ran1 < subsets4yroot5.ran1+ subsets4root5.parent - yroot! else if )subsets4root5.ran1 > subsets4yroot5.ran1+ subsets4yroot5.parent - root! // 0f ran1s are same7 then ma1e one as root and increment // its ran1 by one else subsets4yroot5.parent - root! subsets4root5.ran133! $ $ // Compare t'o edges according to their 'eights. // sed in Rsort)+ for sorting an array of edges int myComp)const *oid" a7 const *oid" b+ struct 6dge" a - )struct 6dge"+a! struct 6dge" b - )struct 6dge"+b! return a>'eight > b>'eight! $ // 8he main function to construct K%8 using Trus1alHs algorithm *oid Trus1alK%8)struct ,raph" graph+
28
int ( - graph>(! struct 6dge result4(5! // 8nis 'ill store the resultant K%8 int e - 2! // An inde *ariable7 used for result45 int i - 2! // An inde *ariable7 used for sorted edges // %tep I %ort all the edges in nondecreasing order of their 'eight // 0f 'e are not allo'ed to change the gi*en graph7 'e can create a copy of // array of edges Rsort)graph>edge7 graph>67 si&eof)graph>edge425+7 myComp+! // Allocate memory for creating ( ssubsets struct subset "subsets )struct subset"+ malloc) ( " si&eof)struct subset+ +! // Create ( subsets 'ith single elements for )int * - 2! * < (! 33*+ subsets4*5.parent - *! subsets4*5.ran1 - 2! $ // Number of edges to be ta1en is eRual to ( 'hile )e < ( + // %tep @I Pic1 the smallest edge. And increment the inde // for net iteration struct 6dge netJedge - graph>edge4i335! int - find)subsets7 netJedge.src+! int y - find)subsets7 netJedge.dest+! // 0f including this edge doesHt cause cycle7 include it // in result and increment the inde of result for net edge if ) S- y+ result4e335 - netJedge! nion)subsets7 7 y+! $ // 6lse discard the netJedge $ // print the contents of result45 to display the built K%8 printf)9Bollo'ing are the edges in the constructed K%8:n9+! for )i - 2! i < e! 33i+ printf)9;d ;d -- ;d:n97 result4i5.src7 result4i5.dest7 result4i5.'eight+! return! $ // ri*er program to test abo*e functions int main)+ /" Let us create follo'ing 'eighted graph 2 2 F : F OF =: F= F : F @ ? "/ int ( - ?! // Number of *ertices in graph int 6 - =! // Number of edges in graph
29
struct ,raph" graph - create,raph)(7 6+!
// add edge 2 graph>edge425.src - 2! graph>edge425.dest - ! graph>edge425.'eight - 2! // add edge 2@ graph>edge45.src - 2! graph>edge45.dest - @! graph>edge45.'eight - O! // add edge 2 graph>[email protected] - 2! graph>[email protected] - ! graph>edge4@5.'eight - =! // add edge graph>edge45.src - ! graph>edge45.dest - ! graph>edge45.'eight - =! // add edge @ graph>edge4?5.src - @! graph>edge4?5.dest - ! graph>edge4?5.'eight - ?! Trus1alK%8)graph+! return 2! $
Bollo'ing are the edges in the constructed K%8 @ -- ? 2 -- = 2 -- 2 O( El ogE)orO( El ogV) .Sor t i ngofe dgest ak esO( ELogE)t i me.Af t ers or t i ng,wei t er at e Ti meCompl exi t y: t h r o ug ha l l e dg esan da pp l yfi nd u ni o na l g or i t h m.Th efi ndan du ni o no pe r a t i o nsc ant a k ea t mo stO( L og V)t i me . Soo v er a l l c o mp l e x i t yi sO( EL og E+EL og V)t i me .Th ev a l u eo fEc a nb ea t mo s tV^ 2 ,s oO( L og V)a r eO( L og E) s ame .T he r e f o r e ,o v e r a l l t i mec omp l e x i t yi sO( El o gE)o rO( El o gV)
*nion+ind !lgorithm | Set 2 (*nion By ,an% and Path -ompression" Oc t o be r2 8,2 01 2
I nt hep r e v i o uspo s t ,wei nt r oduc eduni onfi ndal gor i t hm a ndus edi tt od et e ctc y c l ei nag r a ph .Weu se d f ol l owi nguni on( ) andfi n d ( ) o per at i onsf ors ubs et s .
30
// Nai*e implementation of find int find)int parent457 int i+ if )parent4i5 -- + return i! return find)parent7 parent4i5+! $ // Nai*e implementation of union)+ *oid nion)int parent457 int 7 int y+ int set - find)parent7 +! int yset - find)parent7 y+! parent4set5 - yset! $
Theabov euni on( )andfi n d ( )ar enai v eandt hewor s tc as et i mec ompl e xi t yi sl i n ear .Thet r eescr eat edt o r e pr e s en ts ub se t sc anb es k e we da ndca nb ec omel i k eal i n k edl i s t .Fo l l o wi n gi sane x amp l ewo r s t c as e s c ena r i o.
Let there be ? elements 27 7 @7
0nitially all elements are single element subsets. 2 @
o nion)27 +
@
/ 2
o nion)7 @+ @
/ / 2
o nion)@7 + / @ /
31
/ 2 Th ea bo v eo pe r a t i o nsc anbeop t i mi z e dt oO( Logn) i nwor s tc as e.Thei deai st oal wa y sat t ac hs mal l erdept h t r eeundert her ootoft hedeepert r ee.Thi st ec hni quei scal l eduni onbyr ank.Th et e r mr a n ki spr ef er r ed i ns t eadofhei ghtbe cau sei fpat hcompr e ss i ont ec hni que( weha v edi s c us s edi tbel o w)i sus ed,t hen r a n ki snot al wa ysequal t ohei ght .Al s o,s i z e( i npl ac eofhei ght )oft r eesc anal s obeus edas r a n k .Us i ngs i z ea sr a n kal s o y i e l d swo r s tc as et i mec omp l e x i t ya sO( L og n)( Se et hi sf orp r r of )
Let us see the abo*e eample 'ith union by ran1 0nitially all elements are single element subsets. 2 @
o nion)27 +
@
/ 2
o nion)7 @+ / 2
: @
o nion)@7 + / 2
F @
:
Th es e co ndop t i mi z at i o nt on ai v eme t h odi sPat deai st ofl at t ent het r eewhenfi n d ( )i s hCompr essi on.Thei fi nd ( ) n d ( )o c a l l e d.Wh en i scal l edf oranel ementx ,r ootoft het r eei sr et ur ned.Thefi per at i ont r a v er s esupf r om xt ofi n dr o ot .Th ei d eao fp at hc omp r e ss i o ni st oma k et h ef o un dr o ota sp ar e nto fxs ot h atwed on ’ th av et o t r a ver s eal l i nt er medi at enodesagai n.I fxi sr o otofas ubt r ee,t henpat h( t or oot )f r om al lnodesunderxal s o compr ess es.
32
Let the subset 27 7 .. Q$ be represented as belo' and find)+ is called for element . Q /
F
?
/
=
O
:
/
2
:
/
:
hen
:
@
find() is
called for 7 'e tra*erse up and find Q as representati*e
of this subset. ith path compression7 'e also ma1e as child of Q so that 'hen find)+ is called net time for 7 @ or 7 the path to root is reduced.
Q / ? / 2
/
:
=
: O
/
:
/
: @
Th et wot e c hn i q ue sc omp l e me nte ac hot h er .Th et i mec omp l e x i t yofe ac hop er a t i o nsb ec o me sev e ns ma l l e r t hanO( L ogn) .I nf ac t ,amor t i z edt i mec ompl e xi t yeff ec t i v el ybe comess mal lc ons t ant . Fo l l o wi n gi sun i o nb yr a nkan dp at hc omp r e ss i o nb as edi mp l e me nt at i o nt ofin dc y c l ei nag r a ph . // A union by ran1 and path compression based program to detect cycle in a graph #include #include #include // a structure to represent an edge in graph struct 6dge int src7 dest! $! // a structure to represent a graph struct ,raph // (> Number of *ertices7 6> Number of edges int (7 6!
33
// graph is represented as an array of edges struct 6dge" edge! $! struct subset int parent! int ran1! $! // Creates a graph 'ith ( *ertices and 6 edges struct ,raph" create,raph)int (7 int 6+ struct ,raph" graph - )struct ,raph"+ malloc) si&eof)struct ,raph+ +! graph>( - (! graph>6 - 6! graph>edge - )struct 6dge"+ malloc) graph>6 " si&eof) struct 6dge + +! return graph! $ // A utility function to find set of an element i // )uses path compression techniRue+ int find)struct subset subsets457 int i+ // find root and ma1e root as parent of i )path compression+ if )subsets4i5.parent S- i+ subsets4i5.parent - find)subsets7 subsets4i5.parent+! return subsets4i5.parent! $ // A function that does union of t'o sets of and y // )uses union by ran1+ *oid nion)struct subset subsets457 int 7 int y+ int root - find)subsets7 +! int yroot - find)subsets7 y+! // Attach smaller ran1 tree under root of high ran1 tree // )nion by Man1+ if )subsets4root5.ran1 < subsets4yroot5.ran1+ subsets4root5.parent - yroot! else if )subsets4root5.ran1 > subsets4yroot5.ran1+ subsets4yroot5.parent - root! // 0f ran1s are same7 then ma1e one as root and increment // its ran1 by one else subsets4yroot5.parent - root! subsets4root5.ran133! $ $ // 8he main function to chec1 'hether a gi*en graph contains cycle or not int isCycle) struct ,raph" graph + int ( - graph>(!
34
int 6 - graph>6! // Allocate memory for creating ( sets struct subset "subsets )struct subset"+ malloc) ( " si&eof)struct subset+ +! for )int * - 2! * < (! 33*+ subsets4*5.parent - *! subsets4*5.ran1 - 2! $ // 0terate through all edges of graph7 find sets of both // *ertices of e*ery edge7 if sets are same7 then there is // cycle in graph. for)int e - 2! e < 6! 33e+ int - find)subsets7 graph>edge4e5.src+! int y - find)subsets7 graph>edge4e5.dest+! if ) -- y+ return ! nion)subsets7 7 y+! $ return 2! $ // ri*er program to test abo*e functions int main)+ /" Let us create follo'ing graph 2 F : F : @ "/ int ( - 7 6 - ! struct ,raph" graph - create,raph)(7 6+! // add edge 2 graph>edge425.src - 2! graph>edge425.dest - ! // add edge @ graph>edge45.src - ! graph>edge45.dest - @! // add edge 2@ graph>[email protected] - 2! graph>[email protected] - @! if )isCycle)graph++ printf) 9,raph contains cycle9 +! else printf) 9,raph doesnHt contain cycle9+! return 2! $
35
Out put :
,raph contains cycle
*nion+ind !lgorithm | Set . (Detect -ycle in a Graph" Oc t o be r2 8,2 01 2
Adi s j oi nt s etdat as t r uc t ur e i sadat as t r uc t ur et hatk eepst r ac kofasetofel ement spar t i t i onedi nt oanumberof di s j oi nt( nonov er l appi ng)s ubs et s .Auni onfi ndal gor i t hmi sanal gor i t hm t hatper f or mst wous ef ul oper at i on son s uc had at as t r uc t ur e: Det er mi newhi c hs ub se tapar t i c ul arel ementi si n.Thi sc anbeus edf ordet er mi ni ngi ft woel ement sar e Fi nd : i nt h es a mes ub s et . Uni on: J oi nt wos ubs et si nt oas i ngl es ub set . I nt hi spos t ,wewi l l di s cus sanappl i c at i onofDi s j oi ntSetDat aSt r uc t ur e.Theappl i c at i oni st oc hec kwhet hera gi v engr ap hc ont ai nsac y c l eornot . Uni onFi ndAl gor i t hm c anb eu se dt oc he ckwh et h erag r a ph( b ot hd i r e ct e da ndu nd i r e ct e d)c on t a i n sc y c l eo r n ot .No t et h atweh a v ed i s c u s s eda nal gor i t hm t odet ec tc yc l e .Th i si san ot h erme t h odba s edonUn i o nFi n d. Th i sme t h odas s ume st h atg r a phdo es n ’ tc on t a i nan yse l f l o op s. Wec ank eepst r ac koft hes ubs et si na1Dar r a y ,l et scal li tpar ent [ ] . Le tu sc on si dert hef ol l o wi nggr aph:
2 F F
: :
@
Foreac hed ge,mak esubs et sus i ngbo t ht hev er t i c esoft heedg e.I fb ot ht hev er t i c esar ei nt hesamesu bs et ,a c y cl ei sf ound. I ni t i al l y ,al l s l ot sofpar entar r ayar ei ni t i al i zedt o1( meanst her ei sonl yonei t em i nev er ysubs et ) .
36
2
@
Nowpr ocessal l edgesonebyone. Edge01: Fi ndt hes ubs et si nwhi c hv er t i c es0and1ar e.Si n cet he yar ei ndi ff er ents ubs et s ,wet ak et heuni on oft hem.Fort a ki ngt heuni on,ei t hermak enode0aspa r e ntofnode1orv i c ev er s a.
2
@
< is made parent of 2 ) is no' representati*e of
subset 27 $+
Edge12: 1i si ns ubs et1an d2i si ns ub set2.So,t ak euni on.
2
@
< @ is made parent of )@ is no' representati*e of
subset 27 7 @$+
@
Edge02: 0i si ns ubs et2an d2i sal s oi ns ubs et2.He nc e,i nc l udi n gt hi sedgef or msac y c l e. Howsubsetof0i ssameas2? 0>1>2/ /1i spar entof0and2i spar entof1 Ba s edo nt h ea bo v ee x p l a na t i o n,b el o wi st h ec o de : // A unionfind algorithm to detect cycle in a graph #include #include #include // a structure to represent an edge in graph struct 6dge int src7 dest! $! // a structure to represent a graph struct ,raph // (> Number of *ertices7 6> Number of edges int (7 6! // graph is represented as an array of edges struct 6dge" edge! $! // Creates a graph 'ith ( *ertices and 6 edges
37
struct ,raph" create,raph)int (7 int 6+ struct ,raph" graph - )struct ,raph"+ malloc) si&eof)struct ,raph+ +! graph>( - (! graph>6 - 6! graph>edge - )struct 6dge"+ malloc) graph>6 " si&eof) struct 6dge + +! return graph! $ // A utility function to find the subset of an element i int find)int parent457 int i+ if )parent4i5 -- + return i! return find)parent7 parent4i5+! $ // A utility function to do union of t'o subsets *oid nion)int parent457 int 7 int y+ int set - find)parent7 +! int yset - find)parent7 y+! parent4set5 - yset! $ // 8he main function to chec1 'hether a gi*en graph contains cycle or not int isCycle) struct ,raph" graph + // Allocate memory for creating ( subsets int "parent - )int"+ malloc) graph>( " si&eof)int+ +! // 0nitiali&e all subsets as single element sets memset)parent7 7 si&eof)int+ " graph>(+! // 0terate through all edges of graph7 find subset of both // *ertices of e*ery edge7 if both subsets are same7 then there is // cycle in graph. for)int i - 2! i < graph>6! 33i+ int - find)parent7 graph>edge4i5.src+! int y - find)parent7 graph>edge4i5.dest+! if ) -- y+ return ! nion)parent7 7 y+! $ return 2! $ // ri*er program to test abo*e functions int main)+ /" Let us create follo'ing graph 2 F : F : @ "/ struct ,raph" graph - create,raph)7 +!
38
// add edge 2 graph>edge425.src - 2! graph>edge425.dest - ! // add edge @ graph>edge45.src - ! graph>edge45.dest - @! // add edge 2@ graph>[email protected] - 2! graph>[email protected] - @! if )isCycle)graph++ printf) 9,raph contains cycle9 +! else printf) 9,raph doesnHt contain cycle9+! return 2! $
Out put :
,raph contains cycle No t et hatt hei mpl ement at i onof uni on ( ) andfi n d ( ) i sn ai v ean dt a k esO( n )t i mei nwo r s t c as e.Th es eme t h od s c a nb ei mp r o v e dt oO( L og n)u s i n gUni onbyRankorHei ght .Wewi l l s oo nb ed i s c us s i n gUni onbyRank i na s e pa r at ep os t .
ind the num/er of islands Oc t o be r1 7,2 01 2
Gi v e nab oo l e an2 D ma t r i x ,fi n dt h en umb ero fi s l a nd s . Th i si sanv a r i a t i o no ft h es t a nd ar dp r o bl e m:“ Co un t i n gn umb ero fc on ne ct e dc o mp on en t si nau nd i r e ct e d g r a p h ” . Be f o r ewegot ot h ep r o bl e m,l e tu sun de r s t a ndwh ati sac o nn ec t e dc o mp on en t .Aconnect edcomponent o fa n u nd i r e ct e dg r a phi sas ub gr a phi nwh i c he v er yt wov e r t i c e sa r ec o nn ec t e dt oe ac ho t h erb yap at h ( s ) ,a ndwh i c h i sc onnec t edt onoot herv er t i c esout s i det hes ubgr aph. F ore x a mp l e ,t h eg r a p hs h o wnb e l o wh a st h r e ec o n ne c t e dc o mp on en t s .
39
Ag r a phwh er ea l l v e r t i c esar ec o nn ec t e dwi t he ac ho t h er ,h asex a ct l yon ec on ne ct e dc omp on en t ,c o ns i s t i n go f t h ewh ol egr a ph .Su c hg r a phwi t hon l yo nec on ne c t e dc o mp on en ti sc a l l e da sSt r o ng l yCo nn ec t e dGr a ph . Th ep r o bl e mc a nb ee as i l ys o l v e db yap pl y i n gDFS( )o ne ac hc omp on en t .I nea c hDFS( )c a l l ,ac omp on en to ra s ubgr aphi sv i s i t ed.Wewi l lc al l DFSont hene xtun v i s i t edcompone nt .Thenumb erofc al l st oDFS( )gi v est he numberofconnect edcomponent s.BFScanal sobeused. Wha ti sani s l a nd ? Ag r o upo fc on ne ct e d1 sf o r msani s l a nd .Fo re x a mp l e ,t h eb el o w ma t r i xc on t a i n s5i s l a nd s
17 17 27 27 2$7
27 17 27 27 1$7 17 27 27 17 1$7 27 27 27 27 2$7 17 27 17 27 1$
Ac el li n2Dmat r i xc anbec onne ct edt o8nei gh bor s .So,u nl i k es t andar dDFS( ) ,wh er ewer e cur s i v el yc al l f oral l adj ac entv er t i c es ,her ewec anr ec ur s i v ec al l f or8nei ghbor sonl y .Wek eept r ac koft hev i s i t ed1ssot hatt he y ar enotv i s i t edagai n. // Program to count islands in boolean @ matri #include #include #include #define MD = #define CDL = // A function to chec1 if a gi*en cell )ro'7 col+ can be included in B% int is%afe)int K454CDL57 int ro'7 int col7 bool *isited454CDL5+ return )ro' >- 2+ GG )ro' < MD+ GG // ro' number is in range
40
)col >- 2+ GG )col < CDL+ GG // column number is in range )K4ro'54col5 GG S*isited4ro'54col5+! // *alue is and not yet *isited $ // A utility function to do B% for a @ boolean matri. 0t only considers // the neighbors as adjacent *ertices *oid B%)int K454CDL57 int ro'7 int col7 bool *isited454CDL5+ // 8hese arrays are used to get ro' and column numbers of neighbors // of a gi*en cell static int ro'Nbr45 - 7 7 7 27 27 7 7 $! static int colNbr45 - 7 27 7 7 7 7 27 $! // Kar1 this cell as *isited *isited4ro'54col5 - true! // Mecur for all connected neighbours for )int 1 - 2! 1 < ! 331+ if )is%afe)K7 ro' 3 ro'Nbr4157 col 3 colNbr4157 *isited+ + B%)K7 ro' 3 ro'Nbr4157 col 3 colNbr4157 *isited+! $ // 8he main function that returns count of islands in a gi*en boolean // @ matri int count0slands)int K454CDL5+ // Ka1e a bool array to mar1 *isited cells. // 0nitially all cells are un*isited bool *isited4MD54CDL5! memset)*isited7 27 si&eof)*isited++! // 0nitiali&e count as 2 and tra*ese through the all cells of // gi*en matri int count - 2! for )int i - 2! i < MD! 33i+ for )int j - 2! j < CDL! 33j+ if )K4i54j5 GG S*isited4i54j5+ // 0f a cell 'ith *alue is not // *isited yet7 then ne' island found B%)K7 i7 j7 *isited+! // (isit all cells in this island. 33count! // and increment island count $ return count! $ // ri*er program to test abo*e function int main)+ int K454CDL5- 7 7 27 27 2$7 27 7 27 27 $7 7 27 27 7 $7 27 27 27 27 2$7 7 27 7 27 $ $! printf)9Number of islands isI ;d:n97 count0slands)K++! return 2! $
41
Out put :
Number of islands isI = Ti mecompl ex i t y :O( ROW xCOL)
Dynamic Programming | Set .0 (loyd 1arshall !lgorithm" J u n e7 ,2 01 2
TheFl oy dWar s hal l Al gor i t hm i sf ors ol v i ngt heAl l Pai r sShor t es tPat hpr obl em.Thepr obl em i st ofi nds hor t es t di s t anc esbe t weenev er ypai rofv er t i c esi nag i v enedg ewei ght eddi r ec t edGr aph. Exampl e: Input:
graph4545 - 27 0NB7
=7
0NB7 2$7
27
7
0NB$7
0NB7 0NB7 27
$7
0NB7 0NB7 0NB7 2$ $ 'hich represents the follo'ing graph 2
)2+>)+ F
/F:
= F
F
F
F
:F/
F
)+>)@+
Note that the *alue of graph4i54j5 is 2 if i is eRual to j And graph4i54j5 is 0NB )infinite+ if there is no edge from *erte i to j.
Output:
%hortest distance matri
2
=
Q
0NB
2
?
0NB
0NB
2
42
0NB
0NB
0NB
2
Fl oy dWa r s ha l lAl gor i t hm Wei ni t i al i z et hes ol ut i onmat r i xsameast hei nputgr a phmat r i xasafi r s ts t ep.Thenweupdat et hes ol ut i on mat r i xbycons i der i ngal l v er t i c esasani nt er medi at ev er t e x.Thei deai st ooneb yonepi c kal lv er t i c esand updat eal l s hor t es tpat h swhi c hi n cl udet hepi c k edv er t e xasani nt er medi at ev er t e xi nt hes hor t es tpat h.Whe n wepi c kver t e xnumberkasani nt er medi at ev er t e x,weal r eadyha v ec on si der e dv er t i c es{ 0,1,2,. .k 1 }a s i nt er medi at ev er t i c es .Forev er ypai r( i ,j )ofs our c eanddes t i nat i onv er t i c esr es pec t i v el y ,t her ear et wopos si bl e c a s e s . ki snotani nt er medi at ev er t exi ns hor t es tpat hf r om i t oj .Wek eept hev al ueofdi s t [ i ] [ j ]asi ti s . 1) 2) ki sani nt er medi at ev er t exi ns hor t es tpat hf r om i t oj .Weupdat et hev al ueofdi s t [ i ] [ j ]asdi s t [ i ] [ k]+di s t [ k] [ j ] . Thef ol l o wi ngfigu r ei st a kenf r om t heCor menbook .I ts ho wst heabo v eopt i mal s ubs t r u ct ur epr oper t yi nt heal l pai r ssh or t es tpat hpr obl em.
Fol l o wi ngi sC i mpl ement at i onoft heFl o ydWar s hal l al go r i t hm. // Program for Bloyd arshall Algorithm #include // Number of *ertices in the graph #define ( ? /" efine 0nfinite as a large enough *alue. 8his *alue 'ill be used for *ertices not connected to each other "/ #define 0NB QQQQQ // A function to print the solution matri *oid print%olution)int dist454(5+! // %ol*es the allpairs shortest path problem using Bloyd arshall algorithm *oid floydarshell )int graph454(5+ /" dist4545 'ill be the output matri that 'ill finally ha*e the shortest distances bet'een e*ery pair of *ertices "/ int dist4(54(57 i7 j7 1! /" 0nitiali&e the solution matri same as input graph matri. Dr 'e can say the initial *alues of shortest distances are based on shortest paths considering no intermediate *erte. "/ for )i - 2! i < (! i33+
43
for )j - 2! j < (! j33+ dist4i54j5 - graph4i54j5! /" Add all *ertices one by one to the set of intermediate *ertices. > Eefore start of a iteration7 'e ha*e shortest distances bet'een all pairs of *ertices such that the shortest distances consider only the *ertices in set 27 7 @7 .. 1$ as intermediate *ertices. > After the end of a iteration7 *erte no. 1 is added to the set of intermediate *ertices and the set becomes 27 7 @7 .. 1$ "/ for )1 - 2! 1 < (! 133+ // Pic1 all *ertices as source one by one for )i - 2! i < (! i33+ // Pic1 all *ertices as destination for the // abo*e pic1ed source for )j - 2! j < (! j33+ // 0f *erte 1 is on the shortest path from // i to j7 then update the *alue of dist4i54j5 if )dist4i5415 3 dist4154j5 < dist4i54j5+ dist4i54j5 - dist4i5415 3 dist4154j5! $ $ $ // Print the shortest distance matri print%olution)dist+! $ /" A utility function to print solution "/ *oid print%olution)int dist454(5+ printf )9Bollo'ing matri sho's the shortest distances9 9 bet'een e*ery pair of *ertices :n9+! for )int i - 2! i < (! i33+ for )int j - 2! j < (! j33+ if )dist4i54j5 -- 0NB+ printf)9;s97 90NB9+! else printf )9;d97 dist4i54j5+! $ printf)9:n9+! $ $ // dri*er program to test abo*e function int main)+ /" Let us create the follo'ing 'eighted graph 2 )2+>)+ F /F: = F F F F :F/ F )+>)@+ "/ int graph4(54(5 - 27 =7 0NB7 2$7 0NB7 27 7 0NB$7