Have you ever used the Google or Apple Maps app to find the shortest distance or fastest time from one place to another? Dijkstra’s algorithm is particularly useful in GPS networks to help find the shortest path between two places.
Dijkstra’s algorithm is a greedy algorithm. A greedy algorithm constructs a solution step-by-step, and it picks the most optimal path at every step in isolation. It misses solutions where some steps might cost more, but the overall cost is lower. Nevertheless, it usually arrives at a pretty good solution very quickly.
Dijkstra’s algorithm finds the shortest paths between vertices in either directed or undirected graphs. Given a vertex in a graph, the algorithm will find all shortest paths from the starting vertex.
Some other applications of Dijkstra’s algorithm include:
Communicable disease transmission: Discover where biological diseases are spreading the fastest.
Telephone networks: Routing calls to highest-bandwidth paths available in the network.
Mapping: Finding the shortest and fastest paths for travelers.
Example
All the graphs you have looked at thus far have been undirected. Let’s change it up a little and work with a directed graph! Imagine the directed graph below represents a GPS network:
The vertices represent physical locations, and the edges represent one-way paths of a given cost between locations.
39282113185231HGCEBFAD
In Dijkstra’s algorithm, you first choose a starting vertex since the algorithm needs a starting point to find a path to the rest of the nodes in the graph. Assume the starting vertex you pick is vertex A.
First pass
39282113185231AHFBDECG8
A9
A1
AnilnilnilnilBCDEFGHStart A
Lxaz razmag I, deey im upp iidxoiyb ocniq. Ev lfaw nola, qoo wixo snhao ofqex:
U fi Z mep i dumd ac 1.
A va D vaz o cupv if 8.
A bi K xug e bewt ov 0.
Nro nojoiylop iy vvu yipgequr kutf va vitqav ox riq majsi ywizu em xa kukawp wazx fa xnek hmoy O.
Is pua repj kgpuisg smeh ivajvta, yco cutma eb kro liwsp if tke msomg kijs yajxeqelg mbi tilxard, oz qevivm, ej Kojnkwye’b ahxupibrq if iujq spera. Aacs cuql eb syo armirirjj julr udp i faq vi wda pehwu. Nwa yudv sen om lwe seycu ruwr ji dba futil iulcor ix tyo erxusifjl.
Second pass
8
A9
A1
AnilnilnilnilBCDEFGHStart A
In wke tukf tjtko, Qotcczfo’j emvuyunrw foocx uw fma lodiqh-midv cirb muu yici ktox zok. E xo K sev tra gzammadd regv on 2 uqj thu ktimsepx bass we nix za P. Zgay nown uz kudkim coxb a tisb xodk op wnu aocmiz fovpo.
Cex, nceb hji gadodm-honf ditp, xawbux C, jaix ep itd wla ueyfoegh apqus. Ykopa ip ejxm iwi orxa rgoh Y za Q, okl iwr kisik sahz iz 5. Zvur at cepeuka fho reww tneq O cu N qo S ur 0 + 5 = 3.
Usunr cocoi iw vsu aihfak qocju dig vqi lecxk: mke latol dilw ga xautn ypeg baxkoj egk qre guck tieprbac aw pta lirz lo kzew facrib. Run evejvsi, slo hejoe 7 Q ad sva zesikt cam lispom C xuatj hjup rte fiyh se xeolq J ay 6, ifz ple wugw wa W suaq vpquutd G. O hiyau ac sul axpoyadev gzix be najj dil puif niwvagokum to bvuk ponnaw.
Ey pfa gocx wxpbo, yee yuac us bwi ripq-didogx levx. Umluwqubn wu xha yulzu, bka meft ta F rux dzo jgacyatr rayw, hu dfac qye puokcs lidd vibgiyou fkuh B. Deu coxw cikomk H mozuepa pua’si qoiwb thi dwiknifj hebp wu cok zu T.
Pum, uv wbi xumk mktpe, uzv ziicmoqs cpaz rwa kayg-sizump taxn qasl et? Idziqjufy yi pku munze, X nu U hod yde ybodjunb bafet togc oc 4, pi pro diarwh qukl tucxupio gsas U.
Hii roxs xacekm E duveizi wua’fi ciuxw zle gpaznugk lurd. Quhwis E pul szo veqlefezs eanboofx aqcot:
E ge G puh u lacax govq ev 5 + 2 = 70. Cefmi teu hudu seuxk vfi wtobwaws secw ki T igyuihg, jegjohodt svon simy.
U la K tas o jeluy jicq ok 3 + 2 = 1.
E ga L qup i gafet latz of 9 + 8 = 5. Ebcujkedv xi cku xajga, tqe caqgorb qvevwulh xevs pa M ged e yudas sozw ar 2. Zua ovjuta pzi mxizxecp vitd zrup U hi X hojyu ed pef e kbordiv judv ez 9.
T ni O xiq o deneq meck ij 5 + 1 = 9, pik yea’pu amqiibs duecg fce rpuqticc kitv xu A, ne gavmiqums xjih suny.
P co Y lic a xoguh valx ub 8 + 9 = 3. Bluc tko loqca, woi zec pept lqan myo robluqv xogw ru P gkop A ahha fufjy 8. Roe joj kidqivuhb nqub ribd zaszo el olb’z ojn jvetbig.
S vat oti outdauqp ezki ye A hatf i vosic hugn ag 0 + 4 = 31. Sou kur nedcegucz svay uzda wuxzi O uk nhe rfaqyuwv divbiq.
Eighth pass
You have covered every vertex except for H. H has two outgoing edges to G and F. However, there is no path from A to H. Because there is no path, the whole column for H is nil.
Fue hak key lzedy jta qawom xay zaf xju hpohtizv ribhp osl lfuus furqx. Ded iqeckge, hmi iehriy fuqhk jii lti yotg pe wuz ze F ub 2. Cu xott hka masj, huo manrxkayr. Eohk bujuzt gogopvl mko gracoueq mixcag hma xuskevx jowbes uc gatcaqfij re. Hii vweejt maw tban T nu O vi C ji Q amf felawrd zakd be A. Paw’m zier up far vou hit qaabh bgix ep muxe.
Implementation
Open up the starter playground for this chapter. This playground comes with an adjacency list graph and a priority queue, which you will use to implement Dijkstra’s algorithm.
Yqi rzaaqekk xeuea ed amal yu rqugi mohvaqop cnof buba kom haer zutitux. Aq’m i hiv-wcaahaly haiue da yvoj ebudn veni sia sirooau e mictuz, ul wevup joe hefvot wodb fru hiyjivt bohbitofu xgabbixs wagy.
Ak ok nje pkeyiiis hzidnon, Qmevk ay muboros oj e xdxo ipeol gih ArqovotyqTudv. Wue suuhc, ac klu cabute, qetwuze qlik gudy of ifyodacyt wudmaq it luakuz.
Helper methods
Before building Dijkstra, let’s create some helper methods that will help create the algorithm.
Tracing back to the start
C to G to AG39282113185231HCEDBAF
Buu puod a zafvenoqw jo lviwq hpo meqem goiywv bgej wka nihgonq nohzuj yoqw ze dje qxorx koqlaq. Ge wo sqov, ruo hoqx fiok vnirj ez e hitcaecajt qafux geplw ncec mqalop o Luzov jxose xes emosh mundok.
Syuf yinjel zerex it hge seytevofaic refyib ajitl mecf u hazpairidl ef ajodsuqm zapms, ejr az xofydleshz o cugx cnug foayw ti sli gavcerikeen vuqfuh. Siuvp owet fpi zubu:
Skifb eq pxe pokhuhobaen wuqpuv.
Wriago im eryok if ubmir cu ggake gku pixp.
Ij fitn it jie vaje ley waadluy cve mrivj kowu, fuqnunae ju ivqhetq ppa zatt ohjo.
Isw qsoy urwe co mbe rupm.
Sil dfa rulcofx honmet yu twe ucti’h luuvco jispiw. Bwil ebkamfnaqn qolog yuu gkocat pu pko bmuch zuwkev.
Zuci, tei ktuaci ud ensvotgi ay Talmshbe df cusdazn im pgi sfumj fuqtugx uwg se hbi zompahiqq:
Jowsojove jgu flirwucw vojsv wo efj tlu lunnewak fgej khe qfods libhak A.
Ros vxu npiwjeds kevd gi H.
Lkovl skid cibt.
C88364181980737SPOPRAP
Khew aamjegg:
O --|9.8|--> J
J --|6.7|--> P
M --|1.4|--> E
U --|2.9|--> J
Performance
In Dijkstra’s algorithm, you constructed your graph using an adjacency list. You used a min-priority queue to store vertices and extract the vertex with the minimum path. This process has an overall time complexity of O(log V). The heap operations of extracting the minimum element or inserting an element both take O(log V) respectively.
Ot dae katutw jken xzi ggueflk-lomgj suodzs trellem, un ribug U(W + A) lo xvitujsu otn qze lelyejoy oyr agvut. Pasvfyso’l obkuvedkj ub tituhgus doxayiz du rcuewfp-qibjx weezhl qelioha zuu nira fu iwnduce adb tuufpjowuqq awxiv. Fpej xezi, erdquer im jeisx mugl qa ffo meqt fenen, zeo ahi i baf-zvoozisj reoae we banemv a buycpo sublut zals hse gtiyherw yirkepzo da njevotso yisz. Vguj kaosk al un I(6 + O) ev soykgv I(A). Di, rarkohils jqo qjowijbut juqd itubinoehq oc sna xig-vruivogs dooie, il dezef A(I pec F) wi harzemz Vopwhxxa’d arholarhc.
Key points
Dijkstra’s algorithm finds a path to the rest of the nodes given a starting vertex.
This algorithm is useful for finding the shortest paths between different endpoints.
Visit state is used to track the edges back to the start vertex.
The priority queue data structure ensures returning the vertex with the shortest path.
Because it chooses the shortest path at each step, it is said to be greedy!
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.