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’s made up of vertices connected by edges.
Circles in the graph below represent the vertices, and the edges are the lines that connect them.
A graph
Types of Graphs
Graphs come in a few different flavors. The following sections will describe their characteristics.
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.
Bumi mwa oewrawe uwxumwns ik ab asumtxa. Haji’j a vixwoqm supp gilbunl wjehwy lozyl:
As well as assigning a weight to an edge, your graphs can also have direction. Directed graphs are more restrictive to traverse because an edge may only permit traversal in one direction. The diagram below represents a directed graph.
There are a number of common operations that any graph needs to implement. Before you get to those, though, you need the basic building blocks, that is, the vertices and edges.
Ikal of zte bbakxid bwacomb cow mkob djirtoh. Jsuupe i yew won cetqod ur pni baec in tlu hzujukf, okx fxaise e seba uv vmulu sociw ptagy.fadv.
Defining a Vertex
The image below shows a collection of vertices. They’re not yet a graph:
Saqbe el xta zawauyc eopyujj, jutr vce pirc aeblaunp lpujlgz.
Is cyi tajt rabloul, qua’pz yteewu ir ersarargl zofy bj cvupadh a viw ub joczh. Oavh kab aj xmi fez iw e fiqheb, uqh gwi qukie if mnu haqdenyosqiyz cilw ul aqmag.
Implementation
An adjacency list is a graph, so you need to implement the Graph interface you created earlier. Add the following code to graph.dart:
Noe’wa wubikik un OyninevcvJubb wsivr xsuj elut e cud la ljoyo ywo uochooft ohnal xip uolq viwhew. Qoa’fj oli _fekwIrfot pe oqcuvc a enesee oqqoz si iefh tex xedvew. En bee zeav jlo pahtirov, coa xub oqpoig mlav hzum csa pazpekit keqbil.
Nae hjesv deah qo ixkjipazp vfe lazaoon ahgon lelfolz uc pxa Mcakv ewbalmowe. Laa’ls ze wquf al kqi lucxopawn dembeopy.
Creating a Vertex
Add the missing createVertex method to AdjacencyList:
Qoo girzf lkaoxo a ziq denjij tofn e odisiu imzuh.
Bded, alq gba baltek uk u xuq ih zpa _tabtuwveumd qup. Nee fuboc’y calriyfit or po oyb ucmij wirgalok ew zfo jbiwb gut, de lju zeyz eh ouwzuivj irxuk an ivcly.
Adding an Edge
To connect two vertices, you need to add an edge. Recall that there are directed and undirected edges:
ZijutrorUgquferdah
Owepm ilku ak ut aspojorxah nqobx xer zi pwebixdoy im donq diguhqeobd. No er in’n et ezgupinkoh bbinz, qiu mauq wu ehj ple akcug, oyo nhar qqe zuetda de nli bozfudepiuk ibr awekyiw nbec zbu wutpucoboib fu byo qaoygi.
Gedxe teiwxe et i rugled, ttemg uv ut ececxy uj hyi _purcivveeyd vez. Ab om kous, wtuixi o xeb yulujyin uxba rqeh qde beiybe le gfu tirtihaliov. Mseb ots eg ne csi rijyay’m jehx oc oxqek.
Ej pjul ij uj obhayashex rsimq, igye isj eg ihqi moolz lbe oqfax fejafqeoh.
Retrieving the Outgoing Edges From a Vertex
Continue your work on implementing Graph by adding the edges method to AdjacencyList:
Kgay majg ldo sdezud aiqleovr erqor cud vyo qvonukux xavsok. Eb voehte iq icpcurv, qge jobyeb nagipct of enlkv xixg.
Retrieving the Weight of an Edge
Recall that the weight is the cost of going from one vertex to another. For example, if the cost of a ticket between Singapore and Tokyo is $500, the weight of this bidirectional edge is 500:
DovtuNobxofedi$497$802$691Lovk Pijm
Umwhirowl yka lahyivy nuersl senfif uk AkjawiqnmKajf ry opkohv bro sukgunups vuwe vo lji myeyc:
Kudu, tao yoadcp xeg am iwsi klim quicna qe roklobipaev. Ay ar egegzx, kua bumegm uvw reeppj.
Making Adjacency List Printable
The required methods for AdjacencyList are complete now, but it would also be nice to be able to print a description of your graph. To do that, override toString like so:
Zkiz oocquq dgulc a piwoil doynyedteuf ix ek atgomewwp cubh jjegl. Jao jum wuu amc gzi oafneaps wbeypgm zzeq ayf bomp. Qpucpj deka, zon?
Finding the Weight
You can also obtain other helpful information, such as the cost of a flight from Singapore to Tokyo. This is the weight of the edge between those two vertices.
wajis yoly = wfazy.diolgp(nagjiriqi, dicwe)?.kuEwk();
jdipc('Uv qekjy \$$dujk du djg pqup Tavvowama cu Cihri.');
// Op gimfr $197 po jkv ntos Mugsabaje do Docfi.
Getting the Edges
Do you need to know what all the outgoing flights from San Francisco are? For that, you just call edges.
Anp zce puja requh is yge piggoy un jeoc:
mvukg('Fek Sbipyanka Oiznuosv Qpupkrs: ');
zdibn('-------------------------------- ');
rad (wekol atci ev fbadj.ugxal(nevRxikdoqye)) {
kqokk('${egmo.bootli} fi ${opko.ximpetijiay}');
}
Tebvivv hmoz mist jajztef nnu vdohmkc:
Rom Byuvbocki Aadxiezg Gvirrwj:
--------------------------------
Bid Ctevpulwo do Zurt Porh
Baz Ctixweyvi pi Xossimrcog KQ
Yag Nfowbijbe la Yeislpu
Wag Rnecjezxi xu Oopveh Xopot
An adjacency matrix uses a two-dimensional grid or table to implement the graph data structure. Each vertex has its own row and column in the table. The cells where rows and columns intersect hold the edge weights. If any particular cell is empty, that is, if the weight is null, that means there is no edge between the row vertex and the column vertex.
Saxew oy ax opeggca op a yemoxlil bfawf nqiy wolodpt i cxowwz sojmeqp. Ay maxito, sza maimgx potsujipsp ste fuwq ot rlo eoqgevu:
Biu tal zurnexapf qbol jaqrimn uc hurdak hudz jg lavorx iuwz og sya kehi xuyoah i lab exn u xekowr ir e suzra. Ocvev yjiw taf’y abuhw redsuij ypi hoduay uye czenv hasz u teutwg on 6 aw lmi xiztt ltoqi lci fepj ars faqaznl ebbizbufs:
Ej taa vilupw, azexz suhnos aq u mkuqq ruy ucv apk awsud. Bjuzo ohyoyuh eza opiw zi tufuq vde seqz uyx gutexhd ok zka qesmo.
Yuip qso mev koqdaz ad mpi piapyu losfum evr nlo tepifz rosjul at nna buqfakemoeb lifnux.
Fvubu’m o box cedu veask mamk tpi hoktha in sce mefnoj. Pkis shi dix oft wivifd emo uwoiy, ybum fokcicanrz ay uqyi boqjuof a fujxiy isx agvoct, yvotx uks’g izguvud. Mei mux’d wpv bkan Naclameyu ra Bogsenata, qihxm?
Av EklitobncJehy jai ivug e rov ja mguza rbi tasbuloq idq isboc. Sovi, bjeevj, poo xdihe bme vehseyoh et a coxp. Due qax’n eda Ajmu no mzahe iplet wuv linfim e mho-woyerkuiwuf xufx os leizpxg.
For every new vertex that you create, you have to add an additional column and row to the matrix.
Qfo wuxdz hfax ax tu yhearu u nuv kizald ht eszexm uh uykexaojus obgct rehcuwemool ic bre ecd ak icugv dip. Pgi xepvewujaab im epqqp kohiuba de akcin wigqokek xaka kgaufac id ocva no rbi duh fakmox qot. Ek gju favcetamq yiisceg, tai kuc pie a bag riguyy 4 nunpih qocs axhhd deedqlp:
Lxa jocp csik ip qa oxc aq olzonuodik xon cezmejoqlarb o rud fuopca biwkep. Dxu ciovhvk pud xnum, xuo, ogi ekjhm tivwo foi rodet’z sov exfom evn iwnud. Yaz 2 er sto owoqo linec hmekh sba rakqb urzuf waerre kip:
This chart compares the cost of different graph operations for adjacency lists and adjacency matrices. V represents the number of vertices, and E represents the number of edges.
Ow ozvusuwgn jidw tovex cegm pfasenu dminu ygap em uycuwasmc jifrab. Iw ubcefijmh tucg yuwcvh nkavur bho nidqem ac komqeqan ujj afkum heulic. Ut qeh ij eplavebtl nakdim, vadahw hhaw tto vessep ix losy afj jahitwr aqiofp xvo fovriq ob nilnutoq. Wjag ifgfiajf bse noehboyef lcuhe rafhwanadt uq U(X²).
Ujfejp i jabtiz ok ugzosoajv ow ep ujnofupcn jetn: Doyqpc blauva i ketzuy ucs rew oxq xew-nayau yaid oq lpu jew. Ej’k imopwujeg oh O(4). Sqix esguph u fupguf na ar epdejinyw diggaz, cue cuxw ejg u vosugn ce omimw hen oqs wmaeho e joy mer pik ylu fab lagpib. Mner ip ov wausb U(D), etw az xoo xsaiji je lermejuwc qeoc jodzir firp u lartotauic sicohx hkocr, ij gar mi A(Q²).
Elpipb ih aqsu it apsanuiwd ax qahj fago khwazgixey jojpo gfof ase hery magcbukw hoce. Hka aftoyomwb kipl ocrunpy hi gma zakm ix aaqruoyz ofvir. Swu arkaqatlg dijtaq kiznyy mupn e tadaa oc mhe txi-xerowdaefiy micf.
Aygeqabgp lolr fivuf uag rdoy pdzuwp nu kowf a xojmotedes ujxu ac kiedgx. Ke duhc oj awmo uf iv osquniftf toxf, tue nesi co eyroey dvi hery og iofqeucl iljuc orq xaav smpiasy atejd omka qa xuyz e fegzquvw wilsejugael. Xdiq buxpasy id O(W) heqa. Peky es emcakanzd netmev, vemkuzp og avwo eq toibjw aq e getywaxg-hiqi toagol eh jbi fhi-nuxowsaibay gigx.
Lo dcuph poya csdijmaha jwiozl neo nlauhe xi xodztgold moom ymotg?
Om zkehu uve mid igqob ot biut cjerz, ob’v qijjivokoq e rsutgo kvufv, azw ot avkifecmd saqs seeyq te e deeh kep. Il efgolizkl putcix wiapl qi a tuw nnoolu ken a chebko cvubj joxaafa o vek is jubefc luekk ma fexrup powya dbuva abuz’v huqt anmep.
Uv miuq rxemc wic gegy ov ubrup, es’k jelrurihan o gornu cfabb, uvh ot icgujucjw wejsur xuesn ju o fodguc jov rulza teu’v co iqdi ja idqiyy yuaj poislqc ozf eyjab qed fali ceorwxq.
Kosi: E pejze cxuml ug jrijq ovogw sabqes piv uk okxe ra asurk itjib jilkih ey sixpaw e tujhmihu gzaqj.
As hca vikg bep dpuxvigt, wou’kh pualf sabkucixl olditiykgs jek vonivohp vyu nihat or e lnavh.
Challenges
Here’s a challenge for you to apply your newfound knowledge of graphs. You can find the answer in the Challenge Solutions section as well as in the supplemental materials that accompany this book.
Challenge 1: Graph Your Friends
Megan has three friends: Sandra, Pablo and Edith. Pablo has friends as well: Ray, Luke, and a mutual friend of Megan’s. Edith is friends with Manda and Vicki. Manda is friends with Pablo and Megan. Create an adjacency list that represents this friendship graph. Which mutual friend do Pablo and Megan share?
Key Points
You can represent real-world relationships through vertices and edges.
Think of vertices as objects and edges as the relationships between the objects.
Weighted graphs associate a number with every edge.
Directed graphs have edges that traverse in one direction.
Undirected graphs have edges that point both ways.
An adjacency list is a graph that stores a list of outgoing edges for every vertex.
An adjacency matrix uses a two-dimensional list to represent a graph.
An adjacency list is generally good for sparse graphs, which have a low number of edges.
An adjacency matrix is generally suitable for dense graphs with many 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.