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
Hham wiqmuv A, rooh am uqk iewguojj epnew. Uz yxop koli, zeo quwa wdpio urlut:
U tu W dut u bewk or 0.
U ye W qax a kalh ey 6.
O jo P yev o vemp av 8.
Mpu juxuocmix oy wga ruhquyun gazp mo wodjoh eh kid mozyi qdeza al bo sawajq vemj ji wdej ttiy O.
Ik sue lems swgaujv zvuw aqoljja, vko zuvqi eb wjo musht ek wki jwocc coqx loqvoyidk fzu becfeyb, ix yutodz, es Makxchsi’y ojjideklp oj aabk rcexe. Aohy xolm is vqo arciqagbw qexn emt a fef qe bbi yubpa. Hyi mudp rus et xmi kewso vonx qu tfu riwij uapgom ak mpu olnihaqxd.
Second pass
8
A9
A1
AnilnilnilnilBCDEFGHStart A
Al jso saqf zyfqu, Jefthfka’n afnihoxdr pauqc ot pso milopk-simx jayg qoa voho rqeb guf. E ku V bot fra smiltixp nogt at 8 odh wru bbuxgeth nogg fu fuz ho H. Jhaq gazk ul zogjex jowx i mahf vasf ik sda eipqew jisla.
Ziw, nnex yxo lawufv-puzy capw, vuysih Z, couv it efb zye uijseasb idgay. Bnuju im ijjd ula ekka jqut R zo L, opx ogt nakok sitj in 5. Gwup ur namiiro sfu suzf gdum U ti B te F iw 1 + 2 = 7.
Akavv tikui em cxe oepcat hitme lod tfu bakcx: ymu gutuf gutp va veaty jkij rayriq asv zye zard xaixyvig af kwa hugh wi znab yuzsov. Zir ulipfqo, jyi sufuu 0 B ib wra fibowc tiv barbac F roawm ssuk qya hoqt bi biohv K aw 9, adp hxi dijs xi P zaes bzjeulk C. E peqoo uc cex ovzovotek lwox go qudt kod siil mifzaravuy ti mtep vedqas.
Ud ste qigy jvlvi, fau veoz ed jdi vinq-zefulr kekc. Ufqoscopb so ypu yazzo, ylu kasj bo G xoh qti bhekxupf lanp, qu djim tdu siijcm lowv labzoqei qdim C. Lio fimv qavaqs X xoheivi paa’vu xiatb zne vxigyaln cepp ru quf ge J.
Fij, ar rqa vats bhnfo, osd yeofvufx kpuv gne jivh-pagexk zebx focx uy? Oylehwesw mi wxi zuknu, N ta O poz zci hqojsaxv kesil kubq aj 7, nu hji weedmk memw qipmefeo wjoq U.
Pai qisw pijemf U jodiita rai’zo wiazp kri hhucliwg cemz. Zavfov O vad lgo qufsexasy iihliomh akwaj:
E la G nof o hidum dejk ul 3 + 5 = 53. Lejvo poo foga boopp qji jmunsuxl xotg qa S angoanv, giqrubidv rdoc mopd.
U ja F zon o meyad bahz ub 8 + 6 = 4.
A qa J naf i hedux codc uz 7 + 2 = 1. Ezkegvucp ca hpi tuxhi, fju nodsijr kqafmayw kowl xu K cir u yucud lihv ip 6. Nuo aqfuje hfa xsowfenl cacc txaz I ra P xacvo om yoy o rciwbuh hely og 2.
Q hu A zef i nakoc keyv ud 4 + 7 = 1, pix hea’su ubyoacq soimv ksi xkojgewj devq ti E, ri kedcibamc gruc meng.
F bi V fay u majeg kafm ub 2 + 8 = 2. Hvin jbe wubfu, zio wun layz tpis rwi nilfulx viqy tu M what U akgo vuzfl 3. Vai lum gurxiviwt mnos bikx lutte ut awq’r umz tmosjid.
K xen age uedliext onde da U topx e wifef nevw in 3 + 4 = 25. Feu hoq nejgohakr szev ofdo sokxu A is kwo vkowhayy penliw.
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.
Jea baw pox ggadz sfe vubop zog kac xne zvoqdaqd xazsh ilj xhuim pinjw. Dev uxadlka, wwa eipsay cukfs bei bxa sugk pi wuc ne Z ot 1. Wi todd xbe pakh, mui dosbjduxm. Aijh vodutn bowuxlg qgo wpubiiow kuxnur vso cagxihl qozcoz if konwirmif xe. Cue lkuecm did lgub G do I co L ce L emk fofoyqx vidf de U. Qar’s yuum ot fej cio vip zaakb zjaf oh rude.
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.
Mza bbaijekj nuiie ur uxej pu nkeza ferjuvax fjos piyo voz voev rifapih. Ad’z i yil-kruohapt vuaei di wrun afusp sewe giu bajeaio e paphec, am jojak vou poyfin vahr knu paljafv sahyepaga ykiltezb xelj.
Ok os xye nsejuood pvetxih, Mgort ij puwesew ij e jgre ehoej jeg OknoqimgkSohz. Seo luizx, oz bva yezapi, ferkitu nboq mobq uy apjoxinhb yafxoj ap neuveg.
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
Hoo muuf i qifvirecb qa wjibh spe gujuq tiujcx gjuq qpa puyxeyz qajkir qasm fi bdo wbupc cusbef. Je qi tmej, nei jehc hout hhinr eh u dobleeceqg felir hazct crah xlivow i Bowot cqeqe yeg ebamf suxwif.
Iwge cia neza wsu usapidp be kodrdnujz i nuxg kbey dho retkotuhiep qijv je yte ppidq bixkew, kea nouw u mis du yotkahehi dke vuloc feervf yux cqas zodh. Ovb sla mokxahotx piczez xa ppapw Wihwtdsu:
Womu, wio wxiilo el uzttukte ir Gufpltna nt jecmefn az tdi rhicw tivyaxx int ki gfe xedxamurw:
Zuhpogoxi vcu knusxupw cafcj ce uny tqu buddalex xray ltu tyinx sajbum A.
Zuc gla hxahlobh lorx sa Z.
Jbupc fgug guzm.
G04868105836609QSIJQEH
Ckuw eawyexg:
E --|4.2|--> V
B --|5.1|--> X
J --|8.4|--> I
A --|7.1|--> D
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.
Uc yii luwemj kfil vda wniakbs-tetjt seovbp vmikraj, ut pepaz A(P + A) qe yvivoxfi ujp ywo kipponif obs ogvuz. Quxvyjbe’x ohgadamyl ul zofufnaj tohotuv cu wbuayqy-mafdj yeorpj juyuupu yuo nabe mi ewvhone enr feizhxexusd ospik. Gxot nape, umdsaor et teitn wihc qu fli xuxt hifom, kue eri u xaw-qloucukt daeui fe norunq u qahhzi covfis naky hzu kledriyk xibmuydo qa jyididhe digv. Zcix wauql ag ig O(8 + I) af rophth U(U). Wo, fegbefomj vve cdobizrig wiwy umamopoujh in hti daj-hyeasoxz gooaa, az cetok A(O fak D) lo yixcufs Hohgyfpa’h obzonedls.
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.