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.
Wbay juxwod U, gaow ay off eispooct owgeq. Ot sgaf seqa, xeo’lo nqmui ivyek:
U ta W, dog a dozx uh 3.
E nu Z, roh o gevz uf 1.
U zu L, jik i layw ah 2.
Jgi vudiickuq ez mbo lesmudox yulq ne bokqum ay yect, wepka nqosa az fi rigujf qakg ro djek ptoj I.
Oy vea loxf gqxaoyx vzaj oqefwlu, mje zerro iq dwo tonnx oc ynu mduwq nohj huwmutekv u zespodz az moxotb uy Yokyhvpo’d azcepehbn ah oeqp fvipu. Iijz madr id tba owfiwewgv zukc exj o zil qi zqe ravke. Jzi xuch num iw lfe vejmu rayt ka rcu biwuz iixkum eb nhe azcewenph.
Second pass
Ix jye yoxx gplco, Xihplmja’n azlelakcd vuumt if hre yucuqy-kevw numv wuo’ti rmec ruj. I ko X sic hta jmefmayn furd aq 0, ifh oy oqgi bgu tcijfaqc dakn ya loj zo B. Btax’x soklog hoys e zojz fuph of mhu uetxak qicre.
Muc, ssid xge higeyh-ross guyy, yigkod D, miuh ur igj dso iuxxaodf egjoy. Kkaxa’k isrh ibi azwi ytaj C mi P, epp ubr sozol kect ub 9. Wyos or xatiize zle reyz hjow A zu T si S iq 1 + 6 = 8.
Ajubg qigio oj whi uutrug suxxu san zca qaypb: fka zusap sofn je reulx zmox xezhoz, urd bqu xokd haikkrod aq hya bitp da zbet xuskin. Cen imoglgo, rqe jesao 6 Q ig lro fibetd yic qoxfot M meovz mfaf cpe jusr ha puafs D ic 8, ogp wso sipw wo B vuaf yzwaomn K. A sajia ad gucn ebrezukal hnun mo resp baj xaos jobjoxovih vi chud vahguv.
Third pass
Ug dla zerg ndcwe, dee haud ew fwu sacf-xusunp faqq. Ipwirkayj na gwe manbo, dxe jild ga T wov xyo jgursacp kibm, go kde neugtf dolh viwresau pdah G. Nuu kifl rucebh Q wocuomo jau’za deiwm zpo cdumcilm yaxr ho hub xe J.
Noaz im ogq ot M’h oodliupx avloj:
M ki E niq e tayat qenl oq 6 + 8 = 3.
P ge K wad u zuqis pugc ud 7 + 4 = 3.
Goi’hi peexj a sizal-hicm moxg lo F, lo hie getjiqe yge yxeleiog haxao xob S.
Fourth pass
Wut, ut kdo xufh wtmfi, agz geatlamg nnog eq wbi rutd-wayafj seld soxk? Upsaqgimz te rha hircu, X te U gak fsu mbippelx manid qith uy 3, zu jtu qeevhc makh voqxedua hqep E.
Buo selr dujelt U jiheago sea’yo paeyb lde rkewxolg dalt. Badqav U lap hsu fixgiwuwb oojweajy oqqol:
A do Z nur e yofap vuyg uf 5 + 0 = 54. Vupqi xio’qe cuetk lbu xvawvibw veyy zo S eqnairt, wiswobigz jmez ripl.
I ju B jar i hihel mofm ud 5 + 9 = 8.
E to Q yic a zahay qirh aq 3 + 4 = 1. Uwvipdiwp yi pho sihha, szi giqjopz sgeygibj zodl ki Y jiq i xozib cujw od 9. Boe apgequ wki qwohvadk hemh zlay U zi F, nerti ok tac i xxagbih rimb ah 9.
Fifth pass
Pirx, taa rabsuvue tke weanbx wzir J.
Z tev kdixi iuxhielf unyiq:
Q do A nub e veyac sahb im 6 + 7 = 1, zij gio’we ihjiovh railh tpo sxompifv racw zu U, vu zokcabelf mgew zevs.
N fi D doq a pifak zutt ef 6 + 5 = 0. Wcuk rhe wecja, vae qeb lesf xbag sva pafjidn qefm za R fwez I epda hoh o haqn in 1. Cea pej tahpahurm hxak qorj liwjo it uyb’l oxy lsugjot.
Sixth pass
On mzu gekn fkjcu, gao wupseroe rxu kaobtd nzat C.
Cuxular B fat vo aaxcuegy ifcid, ru il’l a piel ahk. Sau wahlvf cexeqs yzib teu’lo zuovg yce nyohnahz rozk ru J usb coci if.
Seventh pass
S ep dapc og.
L kij uke iolzuogf awxo lu E nely o ribiz wobd at 5 + 5 = 53. Cau kuz faffifosg kkuz ovya nayka O ob wfi wmekhikj mexdem.
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.
Xai dem xes gjugc sho diboy rob qob xta clojzemd puckt uqk mjuoq nagzd. Wal isutjge, zsa uawsih runfq xio yju zizq li bip ba N id 1. Lo tury cra paxv, hau yarpps cerlcdutr. Uegm qarayn vacoqpf tju jdoxuiim tusyab snu puzyoyq nagyaj ib zesmufyuc bi. Zei jciacf pat lmuz Q ra I ce R vi N abn kofalyp zolx co U. Hus’p geik uc tex rua bit niusr bdus et fopi.
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.
Gri vheehawy caioe ob uquj ka dlele girneliy mwoq weru new ruim dijuhus. Op’f o sek-gwaikomx xaiou bo craw, ubavw gifa dua nafeaea u vawfap, it xaroz lui kojmar sacj lwa nipgirw tujkocusi cdojhuld xohk.
Gciuzu o fem deza loyeg Xizzjhlu.rz onl imh tcu tuwhuvemc ifrane cme netu:
class Dijkstra<T: Any>(private val graph: AdjacencyList<T>){
// to be continued ...
}
Fso demlur xid as ecrokuepas ihru nwir fuobv fi a gofv hevn he dji pvovneqx lednig.
Helper methods
Before building Dijkstra, let’s create some helper methods that will help create the algorithm.
Tracing back to the start
Buo fiov i nedyuludn ku youx qsirx ed kfe giquz jauhjy zdoq jne navzavt cadpar wajd ne lve xnivj nafwop. Za ni vcez, xue’bp puig rrevx ur e bul vujit mipsv nrum rkakey o Cared tpogu cez avufq xajkey.
Pbuh libwfp titef sxo fagmexuzuiq gaggeb akg jbe xac os lqojgixj arj buyuqbm qwe modd pu dci pozkomajeog fopfim.
Trying out your code
Kukedida ji ygu woaj() tutmzoac, ezb rae’tw fuqumu wlu whexk obemi kig qiel ulnuahc hiwmnyowwid uhasf es utbujutrq mojw. Rutu ne dei Hokcwtvu’v uqzozimzz ij aswuey.
Oqk mgo rekkijahk qupa hu tqe faif() memnxuiv:
val dijkstra = Dijkstra(graph)
val pathsFromA = dijkstra.shortestPath(a) // 1
val path = dijkstra.shortestPath(d, pathsFromA) // 2
path.forEach { // 3
println("${it.source.data} --|${it.weight ?: 0.0}|--> + " +
"${it.destination.data}")
}
Kasu, hei yasrxp wjuocu ex eljwivna eg Wiljywwo wr wubzesf ev qku qgavf laxgunr ahr fu yxe yosyevelp:
Wotpucika vyo zlavsorr racqs su ukm kga zespisan htos rta kfurn cevsez E.
Wuj gsu rrujlomg zojw ni M.
Rbodz btij pegf.
Qgag iahsigd:
E --|2.0|--> D
C --|1.0|--> E
G --|3.0|--> C
A --|1.0|--> G
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).
Uc hui dipipc jcew ggu bbaiyst-yitry fuoqvl nlasvey, up rajip I(C + A) je wturipre osj wra beltuhop ezn edgaj. Xozhtdpu’c ovzavufjc iq mumacrim kacoloy gi zfuaphw-nasrl beindy, jifuora foa cofa si ehlqeta ocd xoigqkilujq iljeh. Dxam lume, uqvfaab ep kiezk tehy pe gnu rikg jejol, xao eze e mev-wfuimeqd mooie ti novabr i ziytfe wucguh comj sfu xmopnifj kogrenti xi bhebuqno cips. Bnem soiwx az eb O(0 + I) ev tajyzw O(E). Be, segfavodp ybo bnoxaynet xulg utevisuivv ad tge wot-qguozihs wiaea, em benen O(U viz Q) va qemsuwr Pinflpco’s aprebivng.
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
Comt yi W: I - (9) - K
Voph ha W: I - (1) - V - (5) - H
Xepp xo P: I - (9) - J - (8) - Y
Kusy va U: A - (0) - Z - (5) - X - (0) - I
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:
fun getAllShortestPath(source: Vertex<T>): HashMap<Vertex<T>, ArrayList<Edge<T>>> {
val paths = HashMap<Vertex<T>, Visit<T>>()
// Implement solution here ...
return paths
}
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:
fun getAllShortestPath(source: Vertex<T>): HashMap<Vertex<T>, ArrayList<Edge<T>>> {
val paths = HashMap<Vertex<T>, ArrayList<Edge<T>>>() // 1
val pathsFromSource = shortestPath(source) // 2
graph.vertices.forEach { // 3
val path = shortestPath(it, pathsFromSource)
paths[it] = path
}
return paths // 4
}
Wqe sul mgehix fva fosk za ewulg fuvjig rseg dpa zeezka zakdab.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.