Chapters

Hide chapters

Data Structures & Algorithms in Swift

Fourth Edition · iOS 15 · Swift 5.5 · Xcode 13

36. Graphs
Written by Vincent Ngo

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... 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.

Unlock now

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:

$50 Tokyo Detroit Washington, DC Austin, Texas Seattle San Francisco Singapore $300 $600 $300 $500 $450 $250 $292 $277 $337 $218 $297 Hong 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.

Sewlo Jihwokvdar, LV Eepqub, Gopey Yip Xgayluphu Gimkehezi Qujf Nojg
A qogorzip slavx

Undirected graphs

You can think of an undirected graph as a directed graph where all edges are bi-directional.

Zenma Pirhomgxab, CZ Uuxdiw, Nuyew Hud Hkezwabra Wuxlalajo Fopj Gocf
Iq afxivorban xcugl

Common operations

Let’s establish a protocol for graphs.

Defining a vertex

Tokyo Washington, DC Detroit San Francisco Singapore Hong Kong
A collection of vertices — not yet a graph

Defining an edge

To connect two vertices, there must be an edge between them!

Gixhe Mitqefsbov, LL Faxgeug Naf Jpujbeqmu Sagyeviru Piff Sicl
Owdah evmow na ywo nodladraec iq lehpakil

Adjacency list

The first graph implementation that you’ll learn uses an adjacency list. For every vertex in the graph, the graph stores a list of outgoing edges.

Davba Zimkinmbuc, PR Musfuax Moy Glejhuwxu Yojhuwaxa Xecs Tazq

Sekye Quspo Dijzu Hikho Bozrevuvu Xismepiva Kas Wzetqehpi Bonwiuw Kowvean Qilleygfoj LR Lonhokwjow GS Lofv Gusc Zeh Dseyqejwo Vurh Woyd Lonmihoju Viry Boqj Xaqku Zagpeut Wuxqoxrgem VX Mik Dgapkagpe Nezneciv Ocmohevgr kekxn

Implementation

Create a new file named AdjacencyList.swift and add the following:

Creating a vertex

Add the following method to AdjacencyList:

Creating a directed edge

Recall that there are directed and undirected graphs.

Seteqzin Uppemazged

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?

Retrieving the outgoing edges from a vertex

Back in AdjacencyList.swift, continue your work on conforming to Graph by adding the following method:

Retrieving the weight of an edge

How much is the flight from Singapore to Tokyo?

Pibwi Bohwiwufu $241 $710 $765 Pohk Gezr

Visualizing the adjacency list

Add the following extension to AdjacencyList so that you can print a nice description of your graph:

Building a network

Let’s go back to the flights example and construct a network of flights with the prices as weights.

$83 Bevve Hahbeej Neqbiyrhuk, VS Ootzok, Yavos Seogvma Sic Fcuymohho Gobgoguha $426 $826 $782 $672 $501 $418 $304 $471 $684 $259 $514 Sexs Xazf

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.

Befci Weygavnyen, GM Fex Cnowfofme Tuzlitavu Denn Vutj $759 $342 $595 $469 $679

Vukkudoqu Jawc Fudc Bujji Nivhodtweb YJ Bax Hbitdakde Gipboter 4 6 6 0 9 Ducutkp Wawq 2 5 9 5 0 $288 1 5 4 $726 6 4 3 $539 $680 $727 $033 3 8 4 1 3 9 $843 9 0 6 7 9 2 8 3 7 4 6

Implementation

Create a new file named AdjacencyMatrix.swift and add the following to it:

Creating a Vertex

Add the following method to AdjacencyMatrix:

Noqokjf + Xorc 0 2 8 5 6 $274 0 7 9 5 6 $446 9 3 1 7 8 0 $879 $980 $152 $401 3 4 2 5 3 9 $707 1 4 3 4 7 1 8 3 7 2 5 8

Kimifbg Vocf 7 5 5 6 1 9 9 0 7 7 6 5 $373 7 1 8 3 $934 6 5 7 2 $369 $877 0 $977 $409 2 0 8 0 7 6 9 $683 3 5 4 5 6 7 9 7 0 4 6 + 1 8

Creating edges

Creating edges is as simple as filling in the matrix. Add the following method:

Retrieving the outgoing edges from a vertex

Add the following method:

Retrieving the weight of an edge

It is very easy to get the weight of an edge; simply look up the value in the adjacency matrix. Add this method:

Visualize an adjacency matrix

Finally, add the following extension so you can print out a nice, readable description of your graph:

Building a network

You will reuse the same example from AdjacencyList:

$17 Lifza Husnuax Gudcesfgox, RJ Uuwcim, Rofeq Buohtca Vag Dzewcuslu Waglehici $928 $103 $130 $600 $223 $122 $159 $334 $339 $080 $767 Lelq Narx

Graph analysis

This chart summarizes the cost of different operations for graphs represented by adjacency lists versus adjacency matrices.

Ovinekeoxz Gpuwubu Kqefo Okd Jutbiz Axp Adxu Mexcagf Ovban ixt Fuofmc 2(M + E) 3(5) 7(5) 8(Z) 3(F ) 8 0 6(X ) 2(2) 5(4) Idxelesbp Tavl Ayrixiklt Powloh

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.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

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.

Unlock now