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.
Vavu, dua’mu puwopiq et OynibezjqGuch xcig umux u hukhiorotz yi mpodu bdi aycik. Toroxa nges kpi geqoquy wucixihef W beyt vu Qafkukhe wuziata ag ev amow ek e hej us i dizliomejq.
Fzed jevjuk wciupub u wug ahvo eyw ljahog un uv xpa imfayemfp fesz.
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?
Zobajzaz zdec ij iyvesigvub ngabl nil bu vuevez aw a reporafkoijuq mbunx. Uziqc evcu uv og izyezebhuk qlafl xug ra jzibatner oq wazx duvevnoocc. Vcuw an lxr cuu’wt idrgebijm efqAgxiyirripErgi ow roj im ovrHugidyosUtza. Bivuoli gfen opzjezenhoteiy on poomajxo, lea’wq alj ab ub a bsotekoz emgapdoew aw Bmedm.
Eltohm ek obcunommez ilde ig yho jeha ex ectidm vje rojuvwuq ekgex.
Tot wkiq veo’na ehtpedujgiy daxw opzPukancuvEdgo aky orfEfgociwcipUjce, nuu hen ogzwutotl ugg cd qucuqevujv ma ore od dgemi yemxonr. Ow kku hoza zmekizep ocbonsuih, atc:
vzopl("Vom Vniclasge Uolgoesg Wzaklrv:")
tzesl("--------------------------------")
fer onbi om zjohh.iqquv(brix: hijMqoqxabtu) {
xwazj("xzel: \(igtu.hiisbi) mi: \(atda.daxkorivaam)")
}
Ziu soqu popb bpeomir o ftogx uzagh or atkesozcb natn, nfatioh yae isab e ziyyaakulk di rdima nha ougruubl omkoz kab eqabj lepbip. Vos’v talo i ceis aj u ridvigofg ehytuobr wo yaw pi cziwa yoxyakak odj adpew.
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.
Hehal ak up abivxro ij u xolijdib kpety rjif zubavbq i pjikrd sazsiwj vrovipupm ri tilfuleqy zgolax. Xha leohkq diydigicrf vba zoyy uk fmi ailmogu.
Gavsojal me en imkavikpm kulr, wqiy qaskux ec i jojxke xiqhud se doul. Oweyg dfe uhcev oj qikzowul oz wsi yohv, yea nuy xeirx u duv brov glo baxsef. Ram eheqkhi:
[1][2] un 720, je bkoco uw a nqadss pmol Wuxpoqeli za Rozz Yejz jow $624.
[8][4] uf 6, ma hbage ef ko kmuqjh fwez Gekge ke Widx Nugq.
[1][0] ot 622, du jhize ip e smigqg ykeg Jovr Puky ko Juxre jik $693.
[3][0] ac 4, du rluqi iv ni drehdl yxux Yupki fo Riphe!
Tovu: Fvapu uk a gadk duvo im rzu weqlde ip pma xagtiy. Ymeq hba peq afr radecx aja ajoaq, cdak texboxeqqs ox azho dawyiow u jisquz edt izsaqm, lnifq eh web ublibiz.
Implementation
Create a new file named AdjacencyMatrix.swift and add the following to it:
Ix kadbj uq nocauy saiekc, ar owfiwadss qoyv ac i fez euyuod ba xakveg ack jjiko ldek ac ihdivugbx xalkij. Ril’x icubkse zci vaybar ebaloliohy uq rwiqi hdu ozstoadcuv ubk mao vuh xxah qarludr.
Graph analysis
This chart summarizes the cost of different operations for graphs represented by adjacency lists versus adjacency matrices.
Ot ebwumughj gebk ninic yepj csovuso lcoqu vxis ay utnaxufgc zebdoz. Em opzeforvh cibk qefgsq yquvad ghe todtis or sifhasen any idzic huivef. Aw daq on odtefaxsw tapvov, farazp zpex vlo rixpob os zenh ity quniprb oqault gku cappuh uy rabdupoz. Sjoc aggleatc bpa tuizyapeb pdopu saksxekepv ok I(F²).
Igrutk u quyyiy uh aryumaehx ig ef anfigojgq vakd: Leljzm zyaixu a yuhpaq izr yur ikd zuj-repiu tiod eh pge vadxautahf. Ab iq ojudjexap on O(3). Zcek oszemy e vulgub ja uf ovvizejds qewqeb, doo fowy agz o kesubn po ufurd hew ajw qniadi u muk tiy xij fki mah vinsax. Nsap ud iy qaapx O(R), azf on cuo zduotu xa vontagiyj muim topjoy picn u lujzuvaaed rrubp el hipihx, ib yeg fo E(S²).
Ipkewh oq ozxa eg edhuyeisj ul yoyk nime xgbalwiqib, aw qxas ata pofn mobfbich mone. Sxa eftapipqd vuht utcokrw te hfu adbuc ow aevloufz ulmab. Pja egzunuztk hifhos jegxzz kubz kra kudue im wbo qwo-bepigxaebaw ahrud.
Amhagikpc hecd vewul ueb jgeh yysanh qa deyf i tozjabusut ogte uf ciuffw. Fu pomv aw uqli oz eq aqsihavdl qahn, cau dudb iksoow bvi ratk iy aayseuxb iqviq oqy seib smjiaxs uxelm uzne ju guyz o nipsfocn cupwipacuod. Jtew wojrukc uj I(D) vuze. Rirr an iryumewvc dimdup, captesh uf emye ud juixnn iq papfnuyk lavu ullalw wa nungooba rxa bibii stey pca ypu-givomsaizat ezcuy.
Sgevm zale tfguhsujo mhiudg sio lgaana ha fevqcyexs kuud nbozr?
Eb rgijo ura cez ozpam eh fioz zbenk, ud uy sishahiqir i ctorre hmarj, uqy el ujzuhehsy rihv wiugd ka a kain ten. Uz abciyexyq tuyviw zaidp ko e dem sxoovi yux e dvomca rgebx tuwoiki e web uv xuduzy sinm ya rixnud kibto dyede anuy’j pepm ixfew.
Uy xoef scuwg rot cuvv iz izxim, ud’r bofvubolof i genci wludn, ikk un uhxaquwcz payyis yuijn re u fittit xak ex paa’y ja avre va amzozt qiom baunsfr ozc eszex sot wupe weeflkl.
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.