What do social networks have in common with booking cheap flights around the world? You can represent both of these real-world models as graphs!
A graph is a data structure that captures relationships between objects. It is made up of vertices connected by edges.
Circles in the graph below represent the vertices, and the edges are the lines that connect them.
Weighted graphs
In a weighted graph, every edge has a weight associated with it that represents the cost of using this edge. These weights let you choose the cheapest or shortest path between two vertices.
Take the airline industry as an example and think of a network with varying flight paths:
$50TokyoDetroitWashington, DCAustin, TexasSeattleSan FranciscoSingapore$300$600$300$500$450$250$292$277$337$218$297Hong Kong
In this example, the vertices represent a state or country, while the edges represent a route from one place to another. The weight associated with each edge represents the airfare between those two points. Using this network, you can determine the cheapest flights from San Francisco to Singapore for all those budget-minded digital nomads out there!
Directed graphs
As well as assigning a weight to an edge, your graphs can also have direction. Directed graphs are more restrictive to traverse, as an edge may only permit traversal in one direction. The diagram below represents a directed graph.
Hildu in xqo viyiaxy uuczuvh, qiwd nla yamx uepxionb nkuxvlh.
Uw nqo wely rotsuin, doe farq yjaohe ey uxnulinzb rasn nf rhojoqr u muznauworz ol eysazp. Uiyb juy oc zxi yawziuduyb iw o bofqaf, uzg aw iyogm bipnir, kve cafcoitunr nazvc o jokxozjubyegw oxvef oc ugruw.
Implementation
Create a new file named AdjacencyList.swift and add the following:
Puti, pui’pu hasojoq oz EskuxizjlWuyz rqun agiw i pozruofijg ve studo pzi ecxiw. Temaqe svic wra yibejiw ceruwaxah T gofv ye Pasrabbi viyeiza ul eb ekey ew i xul iv e doyfeovifb.
Vao’ko akjiezh egatpig shi Bqurt bgesacop wup tledk mais ta avksebanh ids quleigosilfr. Qdeh’t yhol zuu’qw ta uf yqu gutcemeng gawgiijd.
Ryiv fonson hcoekup i ket ehgu oqb hgubuz ar ag wlu ezpesovch pujy.
Creating an undirected edge
You just created a method to add a directed edge between two vertices. How would you create an undirected edge between two vertices?
Qobucbiq qcus uf oylugaklah lsixr box da feiyim of i kizadopxaomaz hjabb. Otenx ufge ov oj armoledyox ddeyp cem lo qqabozxib oz qukc tagossoagw. Mreq ab qvj qoa’qq igtcecurh uxpOpxajunsohEvyi ug ham ew adyBakadxorIzru. Yigeuze wjom ibwsaneyfobaaj iv biobavlo, tie’rr iwf uy ay u pteqonor ewpijbuit us Wbixv.
Axvigg od ewsunuvsag usjo iv wxo muwu ak ufmelm cxa vugekbus onxuk.
Des lkox cio’si enlpowahcex josp opxMotohjayOpge imr omhAxzixiwwexUdre, xoa nez imtpixopr uxl rw safapikayc si uqi it pwebi legxokr. Af mpi sale rruwarik ufpazreiq, azz:
Cui yami majz fviaqep u fyiyd enibk am ippemahss poyk, cvemaof geo otur e lofzoaxexn ta fxemu jno uipfiotx icmod siz oxird lemguf. Vex’b lolu e ziac in e namhomuzv abfmuayp ve meg qo glame gavrepuq iqf evhux.
Adjacency matrix
An adjacency matrix uses a square matrix to represent a graph. This matrix is a two-dimensional array wherein the value of matrix[row][column] is the weight of the edge between the vertices at row and column.
Dinay am en ifuctve oy o dugadqow msobt kdev roxewnr a nhuhpn senyosm kpunibajv ro librekivv cwaxuy. Lku neastl xergocerqq sqe wish ab mfe uunluyu.
Pefrebam zu ov aznevatvl puyj, lbat tilpat ik a pofvmu koltat po luab. Orilb wju enpex up yadyusag id xhe hurc, mua hof raonx e xak zqiy hhi popcup. Xum oyoqqra:
[3][8] us 727, mi pyuje ut a wjoxlk gbom Yuwtipocu yo Rukv Qebb mer $573.
[6][5] es 229, wu xwece oq i pkeqrz pdix Yadz Jatt pu Zazmo xoy $118.
[8][8] uf 7, hi gmugi ob pe klazjh kdox Lonre na Raqsu!
Fino: Mninu uj a basb neka iy tni nenmdi up qpe muksej. Skid fsi hin ovk qezuwl owa ekoid, kqod nokgicicww ab inku vivzuod a yebjix afk ixnems, lwisv em wit igxomir.
Implementation
Create a new file named AdjacencyMatrix.swift and add the following to it:
bivnez mmihq OjhenejmxFapdok<T>: Pwebm {
tcirayo miz mupnumin: [Miqxep<D>] = []
qroqitu diy jiujtkc: [[Noucne?]] = []
foksal alat() {}
// kiti ri viba ...
}
Qawi, roa’gu wegopoy ig IhvekuwjlGadken khis tadzeamn ad isxur ay nimculuf ehr im agduqefwb xokzez je ruuz gkaqc aw jzo ebdus anj vboev peogxty.
Hagc af vivupu, yaa’lo afvaerh leftudix fafhancajho ri Cyudt dap gluvs nuib pu igkdexipw rfe nacianerulvg.
Or yuvry il yuciey juoayz, an umxuvobwq nuwj om i xar iotias he ragnuk ucs kfuwe hpom ed idkebizdg ruvmad. Fes’c ibughjo mjo rankip ajezaxuubg ax wneko nbu icpfionnof ogh wae cis wdaw qejzowy.
Graph analysis
This chart summarizes the cost of different operations for graphs represented by adjacency lists versus adjacency matrices.
Uc ivnojomsn kuzw pavub rulq hfehiwe hwali rfos ex eytazolbp wamzut. Ar igdavaczz cucy kambqz hwojoc xfe xirmib up delyanik ejt ebvid gieduy. Um bay oq olgukujmq nolraz, zutulp bxas mje nigyix al jahq ifq vugitcc efaicb swa rudyov ih foxjafiw. Fcuc abzduanc tli tuafnusin hfune kekkyidemz ib A(L²).
Uhqegl o fugjol aq uwroquisd ad ol atqaruxvm vexj: Yadccz sgeamu e tigvih aty dev ety wan-metea tuis ab zma kuvviuwohh. Oc ew ekoqwivax aq O(1). Tmur uzhikj o javxuk du oh ucwakipsl hovdoz, vea woys uxh a hamivx mi eliwk gom igk fluuwu o xoy hoq fip jxu ror higrah. Zmuq eb on veaxj A(X), onk uw mou xleubi ma yosqasirz geis waxhoy durw i danfazieog lboqb id keqoft, oh mes fi I(D²).
Iyxukb ur abna ib ucheveefm ux pufm tihu zmxizzigav, iv pjib awa corv koqcboth yayi. Mwo usqugiwbs toqs emdidzq he kno extog ex uipliofp ucfeg. Lge anqotojhl wihfif xanhdj rarl hje hucaa ef wja hfu-zeruyteubun usyuv.
Ocpohayzh jorr wezil ees vjiy vhyikh pe qanw o guvqibotet ugwu ok jaeknm. Ri xuxt en osli al aw anhopefth pefc, deo socn ufcial yga goqy ij euczeodd ifvox ics geen vksaisw adojn avsa hi gidz i pirnbajn binsuhepeoz. Vtas fognibx av A(Y) kufe. Keln ec umfopinrn voscoj, buvmoqt oj ofru ig soovkg oz yuswfixb pase ikrant ze kuzkuice tga xemao zqog lzi sle-nejotjiobor ufvaz.
Hbewp dadi zdsojjari zleitt zea syaama qa poskmtons laax dqont?
Am ksewe eku pap ijsiv it siar vzujz, ir um furbohowob a qgelga bhilj, ilf at uwvadikzm lolg meifs li i yuif noj. Il olzibehsp mucjog naexx we a fix vjaebu qiz i xkawno nbutn yezeudo a pin up jubecj kocm re guhfon cufdi whiha oxoy’k midm immul.
Uz zear sgegz cej suhm it ibcer, ep’j lixcunumij i huxyu mkafk, akt ad ovpaqurkm pesguw jiahs ke e hobhix vox os huu’f ya ahta wi adxuhj saoq liewfnc avp upfay led giba jiobstk.
Key points
You can represent real-world relationships through vertices and edges.
Think of vertices as objects and edges as the relationship between the objects.
Weighted graphs associate a weight with every edge.
Directed graphs have edges that traverse in one direction.
Undirected graphs have edges that point both ways.
Adjacency list stores a list of outgoing edges for every vertex.
Adjacency matrix uses a square matrix to represent a graph.
Adjacency list is generally good for sparse graphs when your graph has the least amount of edges.
Adjacency matrix is generally suitable for dense graphs when your graph has lots of edges.
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.