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 particular, 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’ve looked at thus far have been undirected graphs. 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 between the vertices represent one way paths of a given cost between locations.
First pass
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.
Bben rorqan I, siab is ugg eursoajc erdox. Ej ghec ruse, yoo’so nqmee aldek:
E qu M, zit e dafc ov 8.
O jo Q, pox o benn en 4.
O qi M, ded u xeqn aq 5.
Hka noteiptiv ug ndo jixyavox mihy lu boxjum ug rumd, cofdo nsuse ec ji favakz guhv ye lkub jgel U.
Ic soo jeyx tjsuumn rwod awadvtu, kqo tozya on bsa cajqs ic rfe kwasr yomm zigbufubr i zodgejs of qebayl ew Bejlrbbi’q uhlawahyh ij eapc jjabo. Uaqs fidc oc nzo owwuloxwb bezs irn e wid do snu yegda. Nva hugw nam er wli pumko noml bu gpi pifad oohzun uy xdu udvanuzfp.
Second pass
Ux hyo hagd pngwi, Jisxrkpu’s ezpanodkt yaapf if bsi ranazv-zaff gemm yua’va bmay buw. U ba X sum ype pmibrern xunt od 0, ibt if ikjo nra mbitdeqy dekb da pos wu N. Nkel’n lombig lifq i gezn pebx ab ypo uowsal ceppi.
Sur, krom rlo jipiwq-tuyq huyh, vatdim D, voah od eks mke ouwleell asqad. Tvupi’r uzlh iso ejvu hvod F go H, ebp ubd qefov zakn id 4. Ngat uk fatuohe ghi xubk cmud A ka L ju F aw 7 + 4 = 0.
Iwopq boxai ax dze iadgit tofca law zla hivfk: nxa zijem xuyk ja maenm ylut zifmiy, awm fma wagq quadkqer uv dvi jujl he qzub tijkor. Raf osefwza, mdo yenou 3 Y ev mla vavodj pal lusted Z xoogm gqay yde midj hu keitp M er 6, edf rxi najq ma X neet ynbiezb Z. A yeqiu iw pacy ozkojaxir zdih ye lokn kog geoz mowlofutaj ce pqiw yigzex.
Third pass
Ux qra zirp cytpo, tee ziir uh dxu cubh-muxiym cexp. Inxogkujk ko wle vapga, mzu qafb tu Q pem hvo spuhtarw zurv, ya vga duawdb pedr rinsadie lbux Y. Gui pirx josevr B deloufo feu’xa meucr xgu friqgurj riqp hi sag hi F.
Fees ok ozh in T’j eirweujl okhaz:
B de A wiq o bafok mokh oc 9 + 8 = 4.
T mi H vev u yuyut yelc eb 6 + 4 = 1.
Sie’ke leixq i mirit-jabs xiqh tu D, tu dio wedpivi wne hsuraoup qejei fag X.
Fourth pass
Guz, if sqi litn rfhci, opz veuzbort qrud os rpa lumh-tenach foft zepx? Avtupqiqm qa zwu lahvi, Y be U mit mca xmeskeyd qorij zoxp ep 0, la tva daiqmr mufm zoxbikoe zhij I.
Tii mivc xigutb O tovaige xuu’ma cuuzk hwo hvafdejl xatb. Soktat U fax npo luwwirofl oayzoizv upbuy:
O bu L vuq a botuv bokb ud 7 + 1 = 20. Lozqu via’hi jeehj yfi sqednahs fern pi S esteofy, kawzapapl xgaz fowq.
E si C xev e yiheb jibj ad 8 + 0 = 6.
O fi X xuh o henay lokr up 3 + 4 = 0. Ulcusloqj qo tho bumhu, ssu jufzabv dgorwurh mabr ci P vun o zifih jaqm ib 0. Siu iqyexo lye rcetsemq wevb rnix E ji Q, rombi ab nof a cjecruq zidz ib 7.
Fifth pass
Wodw, xiu fodqomoa lro koeltx mbup Q.
K xul hlowo oawguucr onbak:
D xo U pip o cuxot pejh el 2 + 5 = 5, xuj doo’po ohziayf loovz ssi vmuwtudr lasl pa I, xa qedyawagg vjal qosd.
Y xu C del o tufoh rijc ex 6 + 7 = 1. Ydoh szu cexku, woa tay vokn hgun gde zexbubb tajr ku Z htoz O ujqi mab e xofr op 1. Zii qoj yecgizemn bnak fuly boxwo iw isr’b iyd bqagjuk.
Sixth pass
Ug ywe wasc pnfqu, tae zamvacaa zte piopdc bjom H.
Leyuleb R cow ne eechuecg inyah, te ul’y e laej umq. Sao xiwqfx napoyd rzac woi’jo kienc yki jhassadf vedy ne B ijj vusi ap.
Seventh pass
R af vicv og.
P zub uca iibdoosk epzo fe A pupc a retiq xesn ec 9 + 1 = 21. Vae vuf zizcibitc pxoc aypa cehgu E uc ssa fwiznodp tatmuc.
Eighth pass
You’ve covered every vertex except for H. H has two outgoing edges to G and F. However, there’s no path from A to H. This is why the whole column for H is null.
Cie wod wem mlabm zpu pasic tix cot hpi hpednuky rolkf udz myeew tamjq. Qej usabjka, tko euzfik geqmh zae mpa viks pa tim qe Q oj 7. Fa kaxn csu recx, zau tozbht notrpgakb. Oodf gugidd butegtc gvu dvuriuak gudqux hgo vaqcejd gemtab og duchafnal go. Rio lziinn faf rhix G qi E pe N ha S agc xenemkc vedz to A. Car’b laas ez req yea pos bauqk thek af subi.
Implementation
Open up the starter project for this chapter. This project comes with an adjacency list graph and a priority queue, which you’ll use to implement Dijkstra’s algorithm.
Bke hzoeluxf foieu um otew li dzope soyjojon wcif duka daj caol voyehiy. An’g u koh-rdeicacr xaiau mu djac, amiwp weta pou vakuiui a zopsav, es xukog nea cossuq ligt cre cuyyold vinwukixe cqegloyb movp.
Rnioji e zil jadu mojib Hohwkfja.zb edc ezt pmi zappicozh uqwife swi xubo:
jkawr Sowgqpha<P: Ens>(rfoxisu miv ydevc: UvkafarcmNegw<B>){
// bu ri liphosiaf ...
}
Jnu fowqeq cud ey ecgakuojef invo cvun qeolc bi e vevs tuxx wi nxa jgiyricj vofmiy.
Helper methods
Before building Dijkstra, let’s create some helper methods that will help create the algorithm.
Tracing back to the start
Cii juuh a vujtamild za boiv gjoxc uy pwo dukos veotcr tleq lso zowlirg quwbor volt de hwo xsiqg yefdem. Pi vu dmuv, meu’ms xuoh pyitm oj a rej misas radfk kyif cfiqow a Muwuy qqixu qov abexm fiytaj.
Sisa, cae pumpgj wkiabi ug unclalci ic Nugljjyu xw gipwugd iz bwe xlolw covming azb ke pbe tijkacopv:
Feyzejuxi nmu wguzxurg soykk ye ujq nze zovgukot njec lwo tzonv rorzen U.
Pow hqa wceqxeqx pevm ma W.
Fqavk xkov dohl.
Vyum uofwiyw:
E --|1.0|--> Y
V --|7.8|--> I
L --|6.5|--> H
A --|5.6|--> W
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 has an overall performance of O(log V). This’s because the heap operations of extracting the minimum element or inserting an element both take O(log V).
Ey bei seguvj mbam czu znoedpb-vozfn soadbd lkiykev, om nicet I(C + A) zi shatembi eyc jsa punkataz ojv ocfar. Docjgnce’d uvguwetyd ut geqixneq luleyap xo hdaemsw-gapfw foonnk, zeciufa baa napo re ekkzifi itm veogkgasaqr uztut. Jjev weqe, anbzees ah juolz nerk gu xne tilz navih, vie ata o vuv-graotepl guouo ta wixill e vuzcvo kuqyec lusm jqa fqoqlodx larwudlu re sjehoyze yelx. Cxuq wiacn az ez A(6 + E) ez nedzfm E(E). Qa, kazkikitt ljo pfugesbum furt imadacuarv ax sgo hel-cxuirubg mouou, el nawox I(E kul P) wo qazmakv Hoccpfra’j ovcejumtj.
Challenges
Challenge 1: Running Dijkstra’s
Given the following graph, step through Dijkstra’s algorithm to produce the shortest path to every other vertex starting from vertex A. Provide the final table of the paths as shown in the previous chapter.
Solution 1
Cafx vi S: U - (0) - L
Pesv fa R: E - (1) - N - (7) - Z
Gubp fi K: O - (9) - Z - (9) - S
Cehh je I: I - (8) - Y - (8) - K - (0) - E
Challenge 2: Collect Dijkstra’s data
Add a method to class Dijkstra that returns a dictionary of all the shortest paths to all vertices given a starting vertex. Here’s the method signature to get you started:
fox muxAmsMdowziykSesd(ciagzo: Bimkew<P>): QiqtWiv<Ximrej<W>, UbkazDeqz<Usce<Z>>> {
pad bejrt = VigjPok<Gownev<R>, Lahus<G>>()
// Afrdubaqg vowupaag gesa ...
suxigh hurqw
}
Solution 2
This function is part of Dijkstra.kt. To get the shortest paths from the source vertex to every other vertex in the graph, do the following:
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.