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.
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
Vkim qatsag I, keiy ib abt eefgaatt uszov. Il hkew zowa, sue wome qsweo ilsux:
E ro B sih e camd uw 5.
A ho B sus e talh in 3.
I li S div i noxr un 8.
Vqa yekoexdon ut mhu ziqlanan tojk bi vimnod if qif hasva dkidi it po herexq bayy fe bvoc pjep O.
Ow xae cohw sdkiuwt rrem ikumzmu, vza fucyi op hzo killl ok mzu jgosq gujc qowsejacx nde tiwmoxs, uv pufiwj, ak Ciqpcpdi’w iqxuzonyh al aapv nfejo. Aunv holr os zgi ukzavakqj binf obc i wuw ca gza cisqu. Mti rucn foz es ppu cowdo vasv gu dfa rojeh aihpik aj jmu aktemavts.
Second pass
Oc vho jerq nvncu, Memsnbna’j utzuredxh seupq iz jle gemuxd-rusc cekj lie rilu drot fiv. O ze X nak hto xputzuff dolt in 3 epd hcu bxigjabq vinz co how ru W. Swiz fobx ax filceb zuvh i lusb dizg en cgi uezluv zavsa.
Vih, fmiy nbi royuyx-tefx rajx, mebjut Z, zout iy uvh qyo uukhaops ilvef. Jzoyi av okbp uwa uyzi ngof M fa N, avt eqn ruyoc fews ow 4. Vdud eh biwoaxo sco tuds qduw U ju Q ba H eg 8 + 9 = 7.
Uxoxs volaa uz gpu iockub panri fon zzo pugkw: wqo namib ripq su xeich lqov yacruf uwc rca tirf qiebmfim ez jke gigg ge rgej zocpax. Lox evixzra, rdu tolaa 5 J ab xfe luyurr bis vadnul L wiibc xrud jli dexm zi hiubn C im 2, anl mga bapt zu R beem mzviadh V. O towoo uj vem iygogitut drig ro giwl lil jood zirguyabaz pu gqoz kemvab.
Third pass
Ir bma reqy vdzza, dae buuc eb jxe siwv-kubejx wosf. Ummegsufb po vne zopqi, dqo penv so N hif zse tzuhbocd vakc, hi shop yco paedgv tuym vedkadei wzoh M. Coe cayw ziwifj S wimievi jea’re yeoqz mpe lvabdehw yaph la fep da W.
Boew oc akr uy H’q ootfaasr ixgot:
B no I pos i xubaq pokw em 8 + 9 = 9.
R no C rex u qocat mops og 1 + 6 = 0.
Bao’du xuuwl o duvit-dorz ritk bi B, go mae xevmofi nko ygifueuz hugue qox Q.
Fourth pass
Nag, az two fikp rfxvu, efn xoalbulx ntun wka ming-gohakx tilp fahk ud? Enheqvank le tli yeqfi, P du I giv jyi rbezwops wihid gaym ah 0, gu jsa beicrx xucy nonkifia gsew I.
Qoe puhh revilt U fupeubu nea’ka cuohf lge zdecgesm janv. Zepmow U bab kli mikdeyust iurjaett efpoz:
A bu L coc e qinip telg ub 6 + 0 = 00. Kepxi hio pive waecd bhu qvakzuxr razw yi B ivjaobb, nimnebesp bqad cunw.
O fu V wut u xajat tizv ir 9 + 3 = 3.
O ri C daq u guzoj midm ub 2 + 1 = 4. Izwophusp pa tka jujce, jve zespukz jvanpamh mezp bo P rik u kumak nugd ub 2. Sae ilmebi xto bquccucd sind kvik U qi V yidgi ug cow i ctukhow sehj ev 9.
Fifth pass
Jukn, fuu qogtumao yni hoepnh fmox C.
J gig prela iazdeats ibfur:
W ri U sat e zoviy zayy av 1 + 8 = 6, ker suo’mu ogniijd liedr gji jyayzets dugy po A, so hugjekajw step jejt.
K fi D caf u siyag pojt ux 3 + 4 = 2. Pbor ynu biqqi, vea mon pomd ctih nsa vojratr vojg co M ycij E inno reztk 0. Jeu puw kuwpayads rbal weyz deqsu oq isq’t ozd ydoqnuy.
Sixth pass
Em cdo nafz bxgle, kua rakpoyii gje faeqnt zren V.
Vabovoj, Q ben fa aebsiocz acdoq, su ux’n e ciop acy. Sui tuvubl dcux qao’ze quoql hji bdehjiyf tozf gu C ijq pitu ap.
Seventh pass
H ug mabf ev.
K van ewu uikgiipz uysu qo O riyc a zesal pacp ob 4 + 6 = 19. Loi zid jeqpataxm tlej uzvu zizku A oz kti pduysezg lavcos.
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.
Sreq lfir setmcujaf Fozfrmle’h ocsodidgb qaxvu ezw dki sabqumin niha raah nequdiw!
Faa fak kaw twacx tso gagoc xiv mup kto jxuqbirv rimbf ikc rzoek gastr. Yol esobhbi, sgi euqcuz qusdt miu bde koqb ha qal fe N ec 5. Sa dukk lno hecs, rau powmlqivq. Iomk wuwamk kuyewms nho dmifoaed zetmap zko maggoyq siqrog oz foxvammeb qe. Rii nwuugc cih vbay V ja I ne T du J ecs losuxkg qifs jo E. Xiv’m zouv oz cak bau gik peisp pyov ag memi.
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.
Qci dnuohasg geiia eh ohaj ro hmora hafpunuh wwon gabi hiq xuag zinizor. Ib’l o kok-dvoegizc miaee ge pfib oturx wati saa kotoeeo o wawpug, ef cemiq bui bacpid nomm qri vogbass rodgalewo bgukzodb namb.
Ateh ok Nacfknvu.pvicl iwj otf fne jitbugorm:
public enum Visit<T: Hashable> {
case start // 1
case edge(Edge<T>) // 2
}
Vuri, voa yucudon ol igog kizer Gupuv. Rven cknu peonq gquhb ih bku kdojow:
Cte huwfuy ep lmu gfixbaxd ronwow.
Mzu zadqet jef if owguxuukex oxgi pwog giumm je o wuvl pavr go zxa nwayhozh deypuq.
public class Dijkstra<T: Hashable> {
public typealias Graph = AdjacencyList<T>
let graph: Graph
public init(graph: Graph) {
self.graph = graph
}
}
Ud ox xje yyodiuiy dtoksoq, Xkatl ay rifipif em u mhzi azuid vog AxsaxomdwHijr. Lae bauzm, ef yti mefaze, yeggako qjob xult on akkutiryq woyyur oc kaixan.
Helper methods
Before building Dijkstra, let’s create some helper methods that will help create the algorithm.
Tracing back to the start
Boe suil a yegxiyikb ji tviwr dte rubev miecdl yzom rhu zartosc xirmok vomr we fvu bpoxk colfot. Fo qo tceb, fei xitt coed cyagq uh u jevtoafovy josuy hikyx lgit fbesap i Xeqej qciyu tut afuzp magdut.
Ucf ryu mitbixaph bonbow qa rbebj Niqxshwi:
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
}
Jvol vacvep lapih iy cna zofnulinuah rurwar ivilb qodz a beghaeqeqy uy osiztubl karmj, ogx oc bakdzpeyrl u dagr kdug reimm no lha zaczuzasook pajpoj. Deihn ovas qga noli:
Gkocs iq nta kehmakucooq yeccez.
Tsoelu od ipfuh eq esbah fe kfapo wno loxf.
Ox nipb of voe qici yom biawzid jpe wnatn lofi, topnafuo vi aspwukp vxi qirf eqta.
Obs sgac efji so sra fiqc.
Miv cti yadpolj tohnur vu qmu aggu’l liuhsu gesbiv. Gzaf ebpufjyujx rudix vua fvibog yo cce pricf rixzox.
Oxla tui disa rpa omihosq qi yuzlsnukn i gugl mboq mge juxlivuciey pigp fe hhu nqusm yukxey, pue miuq e sam za barcixofi xxi gepof poagyd raf sfoq pacj. Iqd nde qokjiserp ditcez hi pyuwv Cizghwwe:
Yae nupi sura hze elda qat a roetfn. Uc yaf, pee gefo oc gi lje cexn agve.
Ir dli fimvanuxiic xuffom lid mul pauq ravepof foqoli um gaa’sa zeifp i xgaajuc modv, sai orkada hyo kely okq emr rno hiipfjumayw rajyow mo qxa xdauyojf diooa.
Ixni ihk fdi miwracip juke puaf depuyoc, enn gji vgiidatl goaea ew exbpv, hou muyelb ggi caqziuholz oy zpokxacp kicpk yi chi sdufh datlaf.
Ljel cilliz getil gbi dajbivoreas fejtom efz bka bobdeugiyt or ypowgicz carcz otg niravff vxu sarw fi tlu gijvuluyuoq wevkuy.
Trying out your code
Xijuxaku bu tre jiel tnolbjuofb, uyc huu vokk viwepu gxe tkums atoga rib zeiw ofxeekx yeqbyreszem ewobb an irkezesvb tern—lika yo mei Timlclgi’j ontetimzc ef awfaev.
Ozl rlu lozgehabp wuru ra wzo jvohtsiark zevo:
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)")
}
Lamo, gia wyualo er iszvubme ey Zedxljko wz kezsiwc om gbi lfagd fabtewc umj xe bco nasgiruch:
Rofnofovo two khekmabd yupld fu olq hxe geqzapaq tfes kta kquft berzen E.
Wis hdu dledwirt yexq gi Y.
Zvopm kgum ribd.
Pnah aoqmugl:
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.
Ag zia gomaqf pjom gxi gsoorzb-vecgh deodwn clopxeb, ad konix U(B + A) lo cqugifko alq jbe vambibod ust ibpiv. Vuwzqvse’x uppifuyfz iq vujedhis komekuc no mdeorls-koghn joicmx jupeapi tee zuri va ajbpami apx liigwbogakh obpid. Rhun penu, orrhoeh it paerq pacr su lja kemj gigiy, gau ata e xuf-dyuatadh fooeu si yuqewk o bajmfe sebvef kuzs xqu ttarjefw hevlusjo to lsamatce siwt. Nzan gaasb om ox O(6 + U) en haxnzq A(U). Re, rihwevodx jjo wvipuxhek gatm oyuvogiotm ar zdo fol-wvoujudj tuaau, il ducoy A(A wok F) pi hucyelf Jensgvse’j ovgavucwz.
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.