0% found this document useful (0 votes)
63 views36 pages

Dijkstra

Uploaded by

Scribd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
63 views36 pages

Dijkstra

Uploaded by

Scribd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 36
Find Shortest Paths from Source to al Vertices using Dikstra's Algorithm Q Pe SC ee aac How to find Shortest Paths from Source to all Meee Lee ee roe Psat Me Coe CR eu ee Sea nati aa hau od RUSE gee eet un ic ae eros TT eet MN ere eC hitps www. geeksforgeeks.orgidiksras-shortest-patn-algorthm-greedy-algo-1/ 0123129, 1:10AM Find Shortest Paths from Source to al Vertices using Dikstra’s Algorithm Output:04121921119814 Explanation: The distance from 0 to 1 = 4. The minimum distance from 0 to 2 = 12. 0->1->2 The minimum distance from 0 to 3 = 19. 0->1->2->3 The minimum distance from 0 to 4 = 21. 0->7->6->5->4 The minimum distance from 0 to 5 = 11. 0->7->6->5 The minimum distance from 0 to 6 = 9. 0->7->6 The minimum distance from 0 to 7 = 8. 0->7 The minimum distance from 0 to 8 = 14, 0->1->2->8 Poe Bula tae Clue iml@ i ea mMClbd in O(V2): UN RON eee ea gee ane Re Er pee nc EIU ee Plea a ERa Tan eran * one set contains vertices included in the shortest-path tree, * other set includes vertices not yet included in the shortest-path ea Dea Ree cm Roa eee ies Tre alee to) MER ML he Banu eat CMS et IC * Create a set sptSet (shortest path tree set) that keeps track of vertices Tiree RUA coe an MMe ere Preece Neger Ceteete eG Rar MT em eae Te shortest path-algorthm-g-eedyalgo-7! 112829, 1:10 AM Find Shortest Path rom Source tal Verices using Diss Ago * Assign a distance value to all vertices in the input graph. Initialize all Cece UCOE En a Ue Caren R ae ect U ean cma cease nara a eee cc miles SMM rst delcuna etre) eae Nae a hora sue oc aoe May Cle nen rics ete cli Sieur Ruk ete RU tome ca aes * To update the distance values, iterate through all adjacent Neate RR ean MARU RU cu RUT eee EU MMe atk CCRC Ree cia) SAU RMA CUR Rue cena Dre NA MAN tere Sel RON ae on fet He R Us oan RRC mun aceon) SPT, otherwise not. Array dist[] is used to store the shortest distance Nota O infects EWU UR RU ESC ta ST ee ola To understand the Dijkstra’s Algorithm lets take a graph and find Dee R area oe mer eo) ole lane ae eae ue ea) shortest path-algorthm-greedysalgo-7! 0123129, 1:10AM Find Shortest Paths from Source to al Vertices using Dikstra’s Algorithm Core Ose re aera er Re ecg leek vertices are {0, INF, INF, INF, INF, INF, INF, INF} where INF Te Now pick the vertex with a minimum distance value. The vertex Ois picked, include it in sptSet. So sptSet becomes {0}. After ae MOR Mae eee ee AO eel eas eaooe ON esa ga ei PAE ee ROT) ATT Yee Eee Sead eR el AR oe ee Ra ere UR oe eR Le Ne te reR OE eee ER ae aed included in SPT are shown in green colour. shortest path-algorthm-g-eedyalgo-7! ora et oe eee Oe T oh included in SPT (not in sptSET). The vertex 1 is picked and Ere ee aaa OR ead aoe OTM 2 Ce creel ee Pree aera * The distance value of vertex 2 becomes 12. Coes * Pick the vertex with minimum distance value and not already included in SPT (not in sptSET). Vertex 7 is picked. So sptSet 1072329, 110.0 Find Shores Pats fom Source ol Vera sing DesralsAgortin now becomes {0, 1, 7}. OO en cre lee aa a aA Cece Lom goa ey eu acy ee) eee dye Core (eee eee ed Toh included in SPT (not in sptSET). Vertex 6 is picked. So sptSet now becomes {0, 1, 7, 6}. OO nee ce Cet ea ae a aT distance value of vertex 5 and 8 are updated. shortest path-algorthm-g-eedyalgo-7! We repeat the above steps until sptSet includes all vertices of the MI mae OAC a aad i Rag ada a EOWA RU uae muse OCs sec te PeUrSt MesE stents PSUrst eas Ses Esta nt cac TS Posucn ay PUSS eae ctu cae esa Pym Ltd Bp) Tra Oia aa U LC for (int v = @; v < V3 vet) Sat eee eet) Cree erase en eam Guo void printSolution(int dist[]) A PU eC oc ee for (int i=; i < Vj i++) PS Uscer MR COCOta SEER aE void dijkstra(int graph[V][V], int src) { PCLan esa bool sptSet[V]; 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! SRC ea ae een ICSD) Cree VOM T4468 ene Crete] for (int count = @; count < V - 1; count++) { int u = minDistance(dist, sptSet); sptSet[u] = true; SCC ee ke T=) See dee Ecarr eos Lm Coa ate Aeon) Croat Reedy ear aaa Pettis int main() re Prrar- INA) 2, 0, 0, 0, 8, 0}, ®, ®, @, @, 11, 8 }, 7, ®, 4, ®, @ 2}, ®, 9, 14, @, 0, @}, 9, ®, 10, @, ®, @ }, 14, 10, 0, 2, 0, @}, 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! CCC ae Pa { 8, 11, ®, @, 0, 0, 1, 0,7}, { @, @, 2, @, @, @, 6, 7, @} }5 dijkstra(graph, Coty Esti stra cury PESO CUE oe Eston setts ary Pesan int minDistance(int dist[], bool sptSet[]) { PO Ue Lave Ue for (int v = @; v < V5 vit) if (sptSet[v] == false @& dist[v] <= min) Cr Oe erase Seen Cem UU e void printSolution(int dist[]) { eRe aR Rc Ta CRC a a ean Eco) cout << i <<" \t\t\t\t" << disti] << endl; 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! void dijkstra(int graph[V][V], int re Fran edna Cee Aa Se ae eee Fae aan FESS) Ce een er Oia aon Crees Bea CL ae Fe eae earn int u = minDistance(dist, sptset); sptSet[u] = true; for (int v = @; v < V3 v#+) edhe ea Corre COE OLm ig && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! PsotreC Cor int main() a PCrar-irIN TAG) eee a Pee a OO 11, @, @, ®, 2, 1, 0,7}, Cr a ae Fa A 2 dijkstra(graph, @); peta FU nae Ce ead import java. lang. POC C A st ea Ere aercr eg tees UrT mee int minDistance(int dist[], Boolean sptSet[]) 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! Se mes ar soe ane eC for (int v = @3 v < V3 vee) PC 110g eae Cie r esha crue Peanue Urs SECM Sticstis Cuma ELD) i Una sul Ue One mC ecu eee for (int i= 0; i <¢ V5 itt) ces eer Ce Spr Seen cent is) eee) { PO econ Boolean sptSet[] = new Boolean[V]; for (int i = @; i < V3 its) { Crete Secu LUa I sptSet[i] = false; Crea 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! SC ee eee TT reg UCC emer pac ea Se Cla ean RED) SCR Oe eT) Cert ee isc aTOLS Crees tee acs aes) Cent ose Cs hae printSolution(dist); ote Ca Cdr Smut) a cre n1 6) Pa onec O10 mand CC i eee) ae 4, @, 6, 2}, i Co ae a i Fe a ae a) i , 8, 0, 2, 0, 1, 6 }, i 11, @, @, @, @, 1, 0, 7 }, ; ee a) ShortestPath t = new ShortestPath(); 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! tre osr Cr my Us class Graph() Caer am CTC (tO Peano self.graph = [[@ for column in range(vertices)] for row in range(vertices)] purses Ce seem oe PUG msc eC) om CUR UC ste etc. eee) Praeger Cremer eres SEU Canoe if dist[u] < min and sptset[u] min = dist[u] cua mm ur ct 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! Cea eae teen on Cee Oot ese Cred ed ee) sptset = [False] * self.v ee nae tC cae = self.minDistance(dist, sptSet) Peta ed eet for y in range(self.V) if self.graph[x][y] > ® and sptSet[y] == False and \ Crete eee seer ees 6a Croce ea emeote ces] 6g) PORa Stich stuCrta3) rae g = Graph(9) Pe Ca os Cae cH Pes cy CC [e, CeCe CC cy PCr ae) cy Cr es [8, 11, @ 2, 0, @ 1, @ 7], Pe | i} Pere oa 1C)) 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! Tee UH Eres? Royster uk ae int minDistance(int[] dist, bool[] sptSet) a STO eGe eC Um for (int v = @; v < V3 vee) PC ott eee Rana ne Ores 6a cru ae anor Ur ss void printSolution(int[] dist) i eo Se Gas aCe Sc Parc AU for (int i = @; 4 < Vs itt) cro Cece ee ns Parte 0 ea 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! void dijkstra(int[, ] graph, int src) { Sue ress new int[V]; Coote Be oe a for (int i= 0; i < V5 itt) { Coe meine aU Pats Oey Crease] So CU ae R= Lan ee Ese USCC aerator sptSet[u] = true; for (int v = @; v < V5 vet) 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! Ser sae er) Cert) eects Crees Cee cd aes Crohn ose Cee PS irecotiscuCresa public static void Main() { See Sets ae F Cy EY ) b Ws @ a @ Ca cE Cray GFG t = new GFG(); t.dijkstra(graph, 0); 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! CP red 2, ®, @, 2, 11, @ }, 7, 0, 4, 0, ®, 2}, Carre ae CeCe 14, 10, @, 2, @, @ }, Cae eee @, @, ® 1,7}, @, @, ®, 6, 7,0) )5 function minbistance(dist, sptSet) A Sean Loe San TH ay cane sere Sets kee Ran Fae) a if (sptSet[v] == false @& dist[v] <= min) { eka coer ae a Seam Umar sa function printSolution(dist) a Cee are Ghee ace ue for(let i = 0; i < V; ist) { document.write(i +" \t\t " + Cress ee ECE function dijkstra(graph, src) { oan eS eC (00 Stra TT for(let i = 0; i < V3 i++) 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! Teg eR mn Pats ee eee Crete] Sogetaae a aen E aD) { let u = minDistance(dist, sptSet); Bade for(let v = @; v < V; vet) a SCE aa ees Croat Ean aa dist[u] + graph[u][v] < dist[v]) Cae eats ee Cea Petre CC o Hy eee eee Ce Ce 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! 123, 10M [ee ene aac ee ee ee ee a Co aS (aC ae Ca eee [ @, @ cc er eed a a [8 11, 0, @ 0 2 1, 0,71], (oe Cre eee Dette Ure eae ns @ ry 5) 19 Pan 1 Ey Fy ce Time Complexity: 0(V) Petr Sess) Neto The code calculates the shortest distance but doesn't calculate the Ene ue ene acy an SER at cue aca distance is updated and use it to show the shortest path from source to different vertices. SD aa ech ue een Pema eRe et ure) Sie Seek ecu nue OC eed we are interested only in the shortest distance from the source to a hips www. geeksforgeeks.orgidiksras-shortest-pat-algorth-g 1072329, 110.0 Find Shores Pats fom Source ol Vere sing DksbalsAgortin Pace a ucukcaek ce kecukac hc Ralin ia Cece Rec a ee Tre Mure Reuter eam ata Cuan el ao aa Sele al with the help of a binary heap. Please see Dijkstra's Algorit! rN ance eee none Tate eles De eC a oman Se cM Mace R Ove CM CNR Reged ce ce ae eR CRs co NOSSO Ng see Meco R aM CeCe karan) will lose its fast time complexity. For graphs with negative weight edges and cycles, the Bellman-Ford algorithm can be used, we will eral take et Sse Re eRe Cielcn le Dijkstra’s shortest path algorithm for Adjacency List using Heap in O(E logV): For Dijkstra’s algorithm, it is always recommended to use Heap (or PCA Reais ices Re ete teuee Cetrted ial enc Creel CM mrc an ahucie scr AAG aCe Cla saiiNae ets RUN CRM enim OUR (cane Seat) Pecreeel CMR CCONCRniCn illum Ciutat ecie Cla aaa sent Regal ea aOR CMe Ue oe eae Nga Pee a: MTT gece PRs eg CO ETS a Rue ke Cee NTU RU ee Ue Re Rg ea Mac REC RC eeu R a aa ime te Cn Ure instances, we only consider the instance with minimum distance and eR UCase The time complexity remains O(E * LogV) as there will be at most OY Renee Rue Uda Re) lem Caen en eN7) EOE Cnc e on aur See sect shortest path-algorthm-g-eedyalgo-7! Estat ceed es cee Pero ees Psu eter lee Dome vixs Uae Usa reece int V5 pret rr PT Seta oe LLaN Dy SCT 2 eu ae eC Ue SECs eu Graph: :Graph(int V) { Cree Ere tsaclrv Sana F SM EEC 2 Lae UCR PUL adj[u].push_back(make_pair(v, w)); ERR Tee Coe HCD SCR eas ate ULI) 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! Fist isesme ret C eGR acest roe eerc les Tees cH Wrav ins tiem rtrd QUae LF pq-push(make_pair(@, src)); Chet ea Bear Ciperm el 15 20D mnG PCa 10 Be [a0 sberet sist See UL eee testa) for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = (*i).first; PELs aes ee tL if (dist[v] > dist[u] + weight) { OCC CS Rents Pee Cec esa 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! Preheat rae ee La for (int i = @; i < Vj +41) Petictee NOSE CUM ea eae SD main() Fae a CUO Pa Cee g-addedge(@, 7, 8); Paci eee Pac 1c OO g-addEdge(2, 3, 7); Paci Ce Pac Ce Par eC Peer ee Pac Coe) Pa Ce) g-addEdge(6, 7, 1); Pe CE Pa Cee On Dea TSC Case reemcirne CeCe rand PREECE tice CccUTis Sa EA co eunanE 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! Ee Uae tact OF for (int i= 0; 4 ¢ V5 itt) { ECOL ener Wace tse SOIC 2) etek ea a adj.get(u).add(new iPair(v, w)); adj.get(v).add(new iPair(u, w)); SCR netic eur Ine Cs tetsn cet ee eee Cette eA CU Ce int[] dist = new int[V]; Arrays.fill(dist, Integer.MAX_VALUE) ; pq.add(new iPair(@, sre)); eased ee DITBCMGL EC LOTO DEG int u = pq.poll().second; SCRUM BERETS CCD IEG if (dist[v.first] > dist[u] + v.second) { rer A eas ters eed eee pq-add(new iPair(dist[v.first], v.first)); acu a Sune cee Sr CUae Sea TE an ETS Bcun Tia Suse mate ese static class ipair { SOO iPair(int first, int second) { eR Or aees Urs) See Re 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! Pi SEtse Tea Tuned Pra etc ei Gc seme Fran ancy (oe OOO Pac ACS Pees Perse Pac ene Pees en Pet ene Peer Paes aen Pern Pee em Pee en Pern Pen Paes Coy Oy oe ser aH oa aoe Oy TO sc ay 1s 6) De Pane import heapq FLY TST ere Cae Cake: Stome CIEUO Pot ota set ec SOMO 3) def addEdge(self, u: int, v: int, w: int): self.adj[u].append((v, w)) self.adj[v].append((u, w)) 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! 0123129, 1:10AM Cee acs ete an] heapq-heappush(pq, (2, src)) dist = [float(‘inf')] * self.v Cre ee) rece d, u = heapq.heappop(pq) SR e TC eCmeTSt eet ey] Soe Re Cs Coes) Cre Age es Cems heapq.heappush(pq, (dist[v], v)) Soe UU Cok DH Graph(v) Be Xn er ec en pee er en eC en pee rr en hitps www. geeksforgeeks.orgidiksras-shortest-patn-algorthm-greedy-algo-1/ Pr ene Peer Ce Par ee Pn g-addEdge(6, Pac en g-shortestPath(9) Pee Ses acc ese ae CER PSEC SCM) < private const int INF = 2147483647; Ee Nr Ua private Listeint[]>[] adj; public Graph(int V) a cron this.adj = new List[V]5 for (int i = 0; i < Vv; ist) i this.adj[i] = new Listcint[]>(); + void AddEdge(int u, int v, int w) sadj[u].Add(new intl] { v, w })5 -adj[v]-Add(new intl] { u, w })5 PCRs acu) 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! Sortedset pq = new Sortedset(new DistanceComparer()); Far Oe ene 0 for (int 1 = 0; i < V5 i+) i dist[i] = INF; + pq-Add(new int[] { @ sre }); Crees Rea while (pq.Count > @) i SOR SU ee cs eee Rr PRCA GrU reso SUC cea foreach (int[] adjvertex in this.adj[u]) Pane canes ace Sey if (dist[v] > dist[u] + weight) ce Cea mecha Rents Per Getme tn get tsa Caran oy) 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! OSE See G Gh ae Sere eT for (int i= @; i < vj +44) oot aS cece ee eae ec Pet ESEEeM cl ccc LCC eee CL Ciena Ey : public int Compare(int[] x, int[] y) : “ cele) pt ; ae © ome de or oe OReRI CA + PERSE a public static void Main() a PCE Cer eee CO Par Pa Co PRN en g-AddEdge(1, Pac em Pa en Paci ee Par en Pa en Paris Ce Pac en Pa Co Per Co 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! test Paths from Source to al Vertis using Dikstra’ Pare Cec Pn sO sae) er seeeel ea SEEING Ccraniacan are Sree Om ULSZDF) for(let i = 0; i < Vj i++){ Sree Ses Cm We 108. Ec AD} a Serre eka D ET Serb RSE CCD DE shortestPath(src) a 3.org/dikstas-shotest-patr-algorthm-greedy-algo-7! 0123129, 1:10AM ita eC ME EEKO LO CeCe cree while (pq.length > @) { ee pq.shift(); for(let i = 0; i < this.adjfu].length; i++){ Tae Ee CEST CE trae eee COTE ST ES if (dist[v] > dist[u] + weight) rege aes Ee eee a na aa pq-sort((a, b) =>{ SCC CS) Rae eae ES return a[@] - b[@]; vs COU Stn asa see ue eC} for (let i = 0; i < V; +44) hitps www. geeksforgeeks.orgidiksras-shortest-patn-algorthm-greedy-algo-1/ Prec e cre Ares ar Op Er CRED -addEdge(@, 7, 8); CT eee C16 RAE aCe MED aC CoE CT CoE aT ee aC eC PT Coma Rr Ce aC CARED a COED aC eee Pens aC (leans Nine a ete eee e ry cd ct PE 11 Fy Fy 14 3.orgdikstas-shortest-patr-algorthm-greedy-algo-7! 23:10AM to al Vericos using Dist DTC Aleem een kacht cman eoa ha em aac Auxiliary Space: 0(V) ele Mae eek Crack ne Lae Mencia Reena Path Algorithm using priority queue of STL. Peet na et aU gc Ur eS Co eRCe UR gd secede UCR Reece Sy Rel eR oR al ect you on an exciting journey to master DSA efficiently and on schedule. era as Ct gece ec ae rakes Ce mec RNa oR Ret cl Ci e-y-W ne CD sy Wa Fer) e DSA in Python PLY WBN esta s19 Last Updated : 22 Jun, 2023 Cana Ler egy ie ee eee " SO eee Te Similar Reads Cae cinemas vac aera RL a Pear) Meese eens emt Cece cena ee Shortest paths from all Cesar) Nene EE oy ret Pm nips mw. geeksforgeeks.orgidiksras-shortest-pa-algorithm-g

You might also like