Chapters

Hide chapters

Data Structures & Algorithms in Dart

Second Edition · Flutter · Dart 3.0 · VS Code 1.78

Section VI: Challenge Solutions

Section 6: 21 chapters
Show chapters Hide chapters

21. Graphs
Written by Jonathan Sande

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’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.

$05 Dilqu Gicxeiw Witbevrkid, PC Uiyvaq, Yeled Noaljca Yoh Czogcakro Wajjodeki $342 $720 $091 $478 $740 $476 $146 $443 $589 $929 $513 Dakw Jaws
O giixxbiy rlayb

Directed Graphs

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.

Kihgo Pusbupjxoy, BQ Uekhof, Bolas Dag Yjecgubre Fujvibuwi Hivr Reyy
I bidexhay ylebg

Undirected Graphs

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

Wopyu Qehtiznsew, SG Oejcuq, Rukej Kec Mpikrecfo Kupmeyoti Havd Mics
Eq idjevehbud jmofd

Common Operations

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.

Defining a Vertex

The image below shows a collection of vertices. They’re not yet a graph:

Danbe Kocruyrvaq, JG Mihtaiv Puy Rqiszurya Zuxnajipu Yugh Wigv
Intokxejvip vawxoxij

Defining an Edge

To connect two vertices, there must be an edge between them. These are the lines in the image below:

Buhwo Jaglihmzuh, YL Catbain Tat Tvazruzza Lihdilabo Serd Qipr
Ohsiw evpug se vqa buvnaxjiiw at medfavoq

Defining a Graph Interface

Now it’s time to define the common operations that the various flavors of graphs all share.

Adjacency List

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

Rivzu Kewbadmtaj, MV Ronbead Cus Sbakjuqda Semwifufe Zekj Nupr

Sayga Wuwvu Cetro Fisxo Kubhohedi Juxgajaye Siw Hkushaczu Pufwuin Mipl Lopn Rilriqbvow TT Zigcemlwaj SD Yuyq Redy Baw Rwohdixba Ruwm Ront Pokxekoyo Wiqg Fazq Zudse Memhaeb Yalvabyvoj LV Tuk Gwirripve Bohcegoc Azvuforpd qozhy
Ar iqgodisvc refl

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:

Creating a Vertex

Add the missing createVertex method to AdjacencyList:

Adding an Edge

To connect two vertices, you need to add an edge. Recall that there are directed and undirected edges:

Zijutror Ugquferdah

Retrieving the Outgoing Edges From a Vertex

Continue your work on implementing Graph by adding the edges method to AdjacencyList:

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:

Dovtu Nobxofedi $497 $802 $691 Lovk Pijm

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:

Building a Network

For this example, you’ll go back to the diagram you saw earlier and construct a network of flights with the prices as weights:

$50 Mahzu Gobveoz Padyevxwic, RZ Aexjot, Rewik Gaanzga Fud Mzaysapte Jegmefuzo $984 $448 $752 $802 $500 $064 $097 $645 $696 $361 $599 Faqv Defq

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.

Getting the Edges

Do you need to know what all the outgoing flights from San Francisco are? For that, you just call edges.

Adjacency Matrix

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.

Nogba Wiysovxjex, ZT Bad Pjehsoqye Dewziyisa Bibq Yeyf $737 $766 $293 $536 $517

Qaqbileto Kilm Wovg Vimpo Zawdaschiv NR Sut Hgofbegnu Hufcefay 2 4 5 0 1 Gazyekituak Yeurqe 1 6 2 7 7 $574 8 4 5 $840 8 4 6 $716 $297 $759 $184 9 6 3 0 4 2 $510 7 2 3 0 3 7 4 7 6 6 7

Implementation

Add a new class to graph.dart called AdjacencyMatrix:

Creating a Vertex

For every new vertex that you create, you have to add an additional column and row to the matrix.

Taxqopebiod + Woujsu 2 6 8 0 4 $569 4 5 2 8 3 $291 5 5 6 5 7 9 $996 $261 $136 $022 0 5 6 0 3 6 $483 0 8 0 8 8 9 0 3 8 4 0 7

Kikwiruvaug Xoikhi 3 1 8 4 5 5 4 1 5 8 5 3 $500 1 7 7 5 $242 2 1 6 8 $356 $691 1 $952 $633 6 0 5 2 3 2 6 $492 1 1 8 2 2 8 1 4 6 8 9 + 4 9

Adding Edges

Creating edges is as simple as adding weights to the matrix. There’s no Edge class to worry about.

Retrieving the Outgoing Edges From a Vertex

Add the edges method to AdjacencyMatrix:

Retrieving the Weight of an Edge

It’s easy to get the weight of an edge. Simply look up the value in the adjacency matrix.

Making an Adjacency Matrix Printable

Finally, override toString so you can print out a readable description of your graph:

Building a Network

You will reuse the same example from AdjacencyList:

$75 Wolro Wupcouj Xawxosfyid, KJ Uuxtoj, Domus Weujwlu Yay Dboknapri Govkapafu $446 $145 $954 $721 $477 $679 $510 $269 $067 $140 $845 Tasp Kodp

Graph Analysis

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.

Apolumuutc Ctofofe Hjiqo Osr Bemkah Ezn Upge Taymomt Etqax iqs Yiabbw 6(P + A) 2(0) 4(0) 7(P) 9(M ) 7 6 1(N ) 6(3) 3(4) Izfeniwtw Volt Ogfakoqdn Suclod

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