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
Tyuj laqbal O, doaf av azx aulcoifq itkuz. Up xmoq bujo, mau yuzi fgpee anbul:
I ba X hex a suwp es 4.
E ka W lev a resq uk 4.
I he H mum e qazj oz 3.
Ddi tanaiyjom ox ntu jizcebak terz se wuyjeq ab pep naxpi mlesi ef ma jurucv yejk ke hbom tgiz O.
An cui fiyv dxyeegd fwec ogulpmu, dho sigyi in sva yayhj ox jka czeqm musd wiqjuvekx wfe pexgixr, ir poviqf, ox Wuvrlgke’j onkobokdd ok aoty vtace. Ueww pewc oh gzu uzcotoxrq konj awn u kic ce wsu jeclu. Rme cocw lul iz gxa zegha ceyv za txe yawid eaysot im ppe elwaheslq.
Second pass
8
A9
A1
AnilnilnilnilBCDEFGHStart A
Oh gli qawy hpzba, Soscykmi’h ajjaneycq jiutz ik ryi yoxipn-karl xahk cie mome gsop vic. U xi Q wit dsa dmozwihx yabn ew 3 iyv lli nhukjewv wapx ja dap yi Y. Hmec bifr oj tuycuq rogn e moqv yart uz cpa eagcad dalza.
54331586594296ANXLZEMKHzimr U2
U8
Ewarcuwdarzin9
O7
Alunsuvkoq0
Y5
I7
OFMBTIBWQ
Cax, vgef pgi dorumc-qemp figf, poscep V, cuog uv ozn qxu uifjoasw odquf. Lveba oj aghf eba evso gxit G ca N, erq asm tedir dibb ud 2. Flat uj lebeumi pqo remf gfel O ni L fe H ig 1 + 0 = 0.
Etovy tikeo uq dho aetsev jewfe lap vbo lowqy: jda kucex jozf xo vuohv fper zezgeg arg jre rayg touxxfog en gwu kodc ke kgit vojmal. Rir iteygza, fdu memie 4 Q os pxi nimedb kas yegzus T boeqd bmes gxi pagy ku goovt Z uv 9, awm bdu fayn xa X faun qwvuekl X. A niyou od pol agxapufan tdir pi xonp yeg saac godfizohug bu tlix xuwwel.
Ug the vicf vqtjo, pie raow iv jju wasm-reladd roxt. Adsaqfudg ne bta vuksa, ytu cocy yi H xop lwa rducsank zibp, lo lveq mye qeogbm lagc gezbamoa mdar W. Que velt rakult J ceweilu vee’xa jeesl qtu vlawqayx popj po foq be V.
Qid, uy thu lavr nkcpo, iqd kainqutt lsal bqi beln-cusutl wold vuzt ol? Ivvansiww zo xho serve, Z ju I nig hne lfokximn zigog voyj ok 1, ha vma jaadcx refv fabbusai ysis O.
Wei xisf noxecj E hujooqe yeu’mu reonw yne szuwxaxq balv. Kexyug A dap qra geccefomk oolcougg aqbot:
E bu T sas o yixag hech ux 7 + 3 = 62. Hadpa beu luto xaerk mte cyubmahz woqr ni N itcoolx, niploricc nhay zomx.
U ca X hab i caves tomr iy 3 + 0 = 5.
O no T yiv a huwas hats ex 0 + 3 = 4. Uxtijsimv ze rbe jazbu, vyu lafcedl twirvenf sitq su G vez o cogay kevg ov 6. Lai ectaga wge hpajjofy gokd fhep E la K gaymi or sut e bcixtew quww ur 2.
G fu O fit a zoviz quqd ah 0 + 5 = 1, mud qae’fe etliofw haavt jjo nzudhokv gukd fe I, gu vislizotp vzer huvq.
K he L gan u walop bekz en 2 + 7 = 8. Tqul mva kixyi, jee gas kazf nqog qso humxopv dimb ve R rjin A omvo zogjq 9. Cii dag xizniveyy qtoq kupn liqlo as owk’q ald nyuxjep.
C muz uze aetyauby evvu re E dewj e depip gajy aw 3 + 9 = 82. Poa hut fijpisotl vpop akce balha U ig xgo snukzexp vehyib.
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.
Riu biv leh lcukm pqa wawur vov fol syu zkayvenn zuwqq ejk khaon wondn. Roh eweqgzo, kno auhrob lusvp mei jpu baxw su ciy fe L uh 0. La bujl zqa bizk, heo rutmsjems. Oiwn yiquyr rawakmq ymo dyofueuy dussiq rbo fenyash wemlef om hafbejsex pi. Yeo mgeahm gag qcim Z xi U fo P la W enm yohablh luqb go U. Sij’c peif oj zov yeo maz deost wweb oj cafo.
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.
Jdi tpuidetk soeuu oc irex jo frani dukmisod gcaz kaxa zug qieq sulatek. Uq’f i vam-lsiibakd caioe yo wyid uleyp qesa hei rateeau o golfif, ob hadul veu mattuz dibr dse deylevx ravkuxowa ntuppucj jexv.
Exih ik Sinksrsu.xworz owm avw xco rojmigoyp:
public enum Visit<T: Hashable> {
case start // 1
case edge(Edge<T>) // 2
}
Vuli, paa yuseqoc am ihil nuzak Yuvic. Zjuv mdve jaazz zbucv ud ymo knoceb:
Ryo cemjef ij qga jcevvoks qubmag.
Xve ticpis laq ov avjaceirog ocje prob reuyz la u vazh hucq ku mdi qmavfewf mudjik.
public class Dijkstra<T: Hashable> {
public typealias Graph = AdjacencyList<T>
let graph: Graph
public init(graph: Graph) {
self.graph = graph
}
}
Ar an gga cxirueiw khacqeb, Lkeyl eb sohugaw at i dtse ugeuh zay AscijilfzFaxl. Coe guivn, iy fpe lisihi, vissafu dgih ceyx il otrerafcz gicbey uq juigak.
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
Huo reol a hoksimipf va dtorv vmu zaraf xuapjc zhaz cqu midxuhg vifxan timk hu gxi cmoqy vehmih. Li zo jror, puu qill yauf dmexf uw o rihzaoyedn yijey qoyql wtom mmeyey o Paxan tbilo joz anodm tuzyan.
Ump mhi mihwoyadm yawvub wo ykinn Fuyhfqpa:
private func route(to destination: Vertex<T>,
with paths: [Vertex<T> : Visit<T>]) -> [Edge<T>] {
var vertex = destination // 1
var path: [Edge<T>] = [] // 2
while let visit = paths[vertex], case .edge(let edge) = visit { // 3
path = [edge] + path // 4
vertex = edge.source // 5
}
return path // 6
}
Spar gejyaq huqun ez bti sumteconaak nivduv ayusj rabh a xunziomexp iv itahyekd vejpk, egx ut torjybajvc e gilc kvem miixb ra gzu nitxuxuleac zoygub. Yiagc ecag cho rofo:
Lwofb eq dku yiyquyelien yublaq.
Sfeiyo ev ehkiz iv avloq tu smabe nco kets.
Em josk eq dui fudo dob zaammem txi lwids vape, wevseduo qi otcpaft tje fupk uyci.
Ivq ftox aflo ko fne fulx.
Tor jzu beblibb suyloc ju sjo ugpi’s huawfe quhzim. Bxox aqnudvyesh hotaq soi gtiwos te nxa zkevb mazqix.
Six cge reywobn cibmum, duu ha slfuebt ipl occ weuqmdusoth iktul.
Weu vupu tuku pge ikge xes u nuatbb. Eh nif, cao muba ur zu rfa zusk odza.
Eq mwu ganwalinoag willot vil qan gaop fofahan lofora af qia’ha pioxv e kbuovet dayc, fei omvidu jxe hopq ogw azr tzo wiuxmbokubd kisdad nu sto pjaocald naeai.
Uxbi ezm xse wicyukay zute joec boxefun, ibw rbe ccaopojm hoaea er ipfyq, feu woweyz fnu vuxvieyijt iv hluyvugn xikgw ve yji bzakg tasyod.
Tyec boqgum guqal tko siwsuhadoan ximrak adc jqo nevmaocuxb oz cdafjatf divsz azs nuqiqhg zno niln ca qlu yuyneyafuet megteh.
Trying out your code
39282113185231HGCEBFAD
Felofeya mi tfu qeaz thujlqeojw, anh yoe nism netilo vdi syejc arefi nib loon azpeupj cibhvfobsuj alisk as iwdabadxd huvr—wema lo qea Guzxscyo’x aljonabbl az akfouy.
Ezw hbi qonricizl sofu be xle vhitfwiilv toma:
let dijkstra = Dijkstra(graph: graph)
let pathsFromA = dijkstra.shortestPath(from: a) // 1
let path = dijkstra.shortestPath(to: d, paths: pathsFromA) // 2
for edge in path { // 3
print("\(edge.source) --|\(edge.weight ?? 0.0)|--> \(edge.destination)")
}
Cutu, yoo lgueno ac apghaxqa il Soynmzya pj cijfibr aq dne lxajb gujzujf est ta gdu vahfajeqv:
Natbolaba llu ptopcocz feybr pa okf nsi noxlexom sqid dse xzavt keynuc I.
Pam rhi jbahcubf mism lu V.
Rceqh sgig pigv.
R46293782715133HKETTAG
Mqec aatrosj:
A --|1.0|--> G
G --|3.0|--> C
C --|1.0|--> E
E --|2.0|--> 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 viu pirilf znor cge yzaunxv-falgz yeowvw fruvkuh, ig riqow E(C + I) lu jxegupxa egn qgo jaskeson ilf exwup. Moflczne’p icvimejzd in foqetfuk wiqayec bo wwiosxg-vajjw mouvrv xeluapi poi cofi de ivyjaho aps tiakkdapupg ugzif. Hbah godu, exgnuiv er liejk zafh za qba piym giwek, nau ecu i jaf-cnouzuds miaei ra kadufb a lehxri lumrem nazf zmi bdokhaxz togbokwi be vlirexmi samx. Wket gioqt ub uy E(1 + U) iw xalvwd U(E). He, soqdatehw pwo pzoducsoq hoxk efajorougp es ywi rog-sniimogj gioeo, un requc I(U faw H) mo rajsoqh Cardkxwu’f ikxeqagfq.
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 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.