9.2 Basic graph operations¶
Basic graph operations act on either edges or vertices. Their implementations depend on whether we use an adjacency matrix or an adjacency list.
9.2.1 Adjacency matrix implementation¶
For an undirected graph with \(n\) vertices, Figure 9-7 illustrates the following operations.
- Add or remove an edge: Update the corresponding adjacency matrix entries directly in \(O(1)\) time. Since the graph is undirected, update the entries for both directions.
- Add a vertex: Append a row and a column to the adjacency matrix, filling both with \(0\). This takes \(O(n)\) time.
- Remove a vertex: Remove its row and column from the adjacency matrix. The worst case is removing the first row and column, which shifts \((n-1)^2\) elements up and to the left and takes \(O(n^2)\) time.
- Initialize: Given \(n\) vertices, initialize the vertex list
verticesof length \(n\) in \(O(n)\) time and the \(n \times n\) adjacency matrixadjMatin \(O(n^2)\) time.
Figure 9-7 Initializing an adjacency matrix and adding or removing edges and vertices
Description of Figure 9-7: Adding and removing edges and vertices in an adjacency matrix
An adjacency matrix illustrates the difference between updating individual entries for edges and adding or removing whole rows and columns for vertices.
The order of the vertex list V determines the matrix row and column indices. The headers give both the index and the vertex label. A 1 in M[i,j] means V[i] and V[j] are connected. A 0 means there is no edge.
An undirected edge joins two vertices. Adding or removing it requires updating both symmetric entries, M[i,j] and M[j,i]. Each frame's table shows the entire matrix after the operation.
To add a vertex, append a row and a column of zeros. To remove a vertex, delete its entire row and column. The matrix indices of later vertices decrease, but the vertices keep their identities and labels.
Initialize the five-vertex graph
Initially, V=[1, 3, 2, 5, 4] corresponds to indices 0 through 4 in a 5×5 matrix. The six undirected edges are 1–3, 1–5, 2–3, 2–5, 2–4, and 4–5. Each contributes a symmetric pair of ones. Edge 1–2 is absent.
Adjacency matrix, step 1: complete initial state Row: index / vertex Column 0 / vertex 1 Column 1 / vertex 3 Column 2 / vertex 2 Column 3 / vertex 5 Column 4 / vertex 4 0/1 0 1 0 1 0 1/3 1 0 1 0 0 2/2 0 1 0 1 1 3/5 1 0 1 0 1 4/4 0 0 1 1 0 Add edge 1–2
Vertices 1 and 2 have indices 0 and 2. Add edge 1–2 by changing M[0,2] and M[2,0] from 0 to 1. All other entries stay the same. The matrix is still 5×5, and the graph now has seven edges.
Adjacency matrix, step 2: complete state after adding edge 1–2 Row: index / vertex Column 0 / vertex 1 Column 1 / vertex 3 Column 2 / vertex 2 Column 3 / vertex 5 Column 4 / vertex 4 0/1 0 1 1 1 0 1/3 1 0 1 0 0 2/2 1 1 0 1 1 3/5 1 0 1 0 1 4/4 0 0 1 1 0 Remove edge 1–3
Vertices 1 and 3 have indices 0 and 1. Remove edge 1–3 by changing M[0,1] and M[1,0] from 1 to 0. All other entries stay the same. The matrix is still 5×5, and six edges remain, including 1–2.
Adjacency matrix, step 3: complete state after removing edge 1–3 Row: index / vertex Column 0 / vertex 1 Column 1 / vertex 3 Column 2 / vertex 2 Column 3 / vertex 5 Column 4 / vertex 4 0/1 0 0 1 1 0 1/3 0 0 1 0 0 2/2 1 1 0 1 1 3/5 1 0 1 0 1 4/4 0 0 1 1 0 Add isolated vertex 6
Append isolated vertex 6 to V, giving V=[1, 3, 2, 5, 4, 6]. Its index is 5. The matrix grows to 6×6, with zeros throughout the new row and column. The other entries stay the same, and the graph still has six edges.
Adjacency matrix, step 4: complete state after adding isolated vertex 6 Row: index / vertex Column 0 / vertex 1 Column 1 / vertex 3 Column 2 / vertex 2 Column 3 / vertex 5 Column 4 / vertex 4 Column 5 / vertex 6 0/1 0 0 1 1 0 0 1/3 0 0 1 0 0 0 2/2 1 1 0 1 1 0 3/5 1 0 1 0 1 0 4/4 0 0 1 1 0 0 5/6 0 0 0 0 0 0 Remove vertex 3
Remove the entire row and column for vertex 3 (formerly index 1), along with its only remaining incident edge, 2–3. Edge 1–3 was removed in step 3. V becomes [1, 2, 5, 4, 6], at indices 0 through 4. The matrix shrinks to 5×5, with five edges. The indices of vertices 2, 5, 4, and 6 each decrease by one, but their labels stay the same. For example, vertex 2 moves from index 2 to index 1. Vertex 6 is now at index 4. Its row and column contain only zeros, so it remains isolated.
Adjacency matrix, step 5: complete state after removing vertex 3 Row: index / vertex Column 0 / vertex 1 Column 1 / vertex 2 Column 2 / vertex 5 Column 3 / vertex 4 Column 4 / vertex 6 0/1 0 1 1 0 0 1/2 1 0 1 1 0 2/5 1 1 0 1 0 3/4 0 1 1 0 0 4/6 0 0 0 0 0
The following code implements a graph using an adjacency matrix.
class GraphAdjMat:
"""Undirected graph represented by an adjacency matrix"""
def __init__(self, vertices: list[int], edges: list[list[int]]):
"""Constructor"""
# Vertex list: each element holds a vertex value, and its position is the vertex index
self.vertices: list[int] = []
# Adjacency matrix: row and column indices are vertex indices
self.adj_mat: list[list[int]] = []
# Add a vertex
for val in vertices:
self.add_vertex(val)
# Add an edge
# The entries in edges are vertex indices, that is, indices into vertices
for e in edges:
self.add_edge(e[0], e[1])
def size(self) -> int:
"""Get the vertex count"""
return len(self.vertices)
def add_vertex(self, val: int):
"""Add a vertex"""
n = self.size()
# Append the new vertex value to the vertex list
self.vertices.append(val)
# Add a row to the adjacency matrix
new_row = [0] * n
self.adj_mat.append(new_row)
# Add a column to the adjacency matrix
for row in self.adj_mat:
row.append(0)
def remove_vertex(self, index: int):
"""Remove a vertex"""
if index >= self.size():
raise IndexError()
# Remove the vertex at the specified index from the vertex list
self.vertices.pop(index)
# Remove the row at the specified index from the adjacency matrix
self.adj_mat.pop(index)
# Remove the column at the specified index from the adjacency matrix
for row in self.adj_mat:
row.pop(index)
def add_edge(self, i: int, j: int):
"""Add an edge"""
# Parameters i and j are indices into vertices
# Check for out-of-bounds or equal indices
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j:
raise IndexError()
# An undirected graph has a symmetric adjacency matrix: (i, j) == (j, i)
self.adj_mat[i][j] = 1
self.adj_mat[j][i] = 1
def remove_edge(self, i: int, j: int):
"""Remove an edge"""
# Parameters i and j are indices into vertices
# Check for out-of-bounds or equal indices
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j:
raise IndexError()
self.adj_mat[i][j] = 0
self.adj_mat[j][i] = 0
def print(self):
"""Print the adjacency matrix"""
print("Vertex list =", self.vertices)
print("Adjacency matrix =")
print_matrix(self.adj_mat)
/* Undirected graph represented by an adjacency matrix */
class GraphAdjMat {
vector<int> vertices; // Vertex list: each element holds a vertex value, and its position is the vertex index
vector<vector<int>> adjMat; // Adjacency matrix: row and column indices are vertex indices
public:
/* Constructor */
GraphAdjMat(const vector<int> &vertices, const vector<vector<int>> &edges) {
// Add a vertex
for (int val : vertices) {
addVertex(val);
}
// Add an edge
// The entries in edges are vertex indices, that is, indices into vertices
for (const vector<int> &edge : edges) {
addEdge(edge[0], edge[1]);
}
}
/* Get the vertex count */
int size() const {
return vertices.size();
}
/* Add a vertex */
void addVertex(int val) {
int n = size();
// Append the new vertex value to the vertex list
vertices.push_back(val);
// Add a row to the adjacency matrix
adjMat.emplace_back(vector<int>(n, 0));
// Add a column to the adjacency matrix
for (vector<int> &row : adjMat) {
row.push_back(0);
}
}
/* Remove a vertex */
void removeVertex(int index) {
if (index >= size()) {
throw out_of_range("Vertex does not exist");
}
// Remove the vertex at the specified index from the vertex list
vertices.erase(vertices.begin() + index);
// Remove the row at the specified index from the adjacency matrix
adjMat.erase(adjMat.begin() + index);
// Remove the column at the specified index from the adjacency matrix
for (vector<int> &row : adjMat) {
row.erase(row.begin() + index);
}
}
/* Add an edge */
// Parameters i and j are indices into vertices
void addEdge(int i, int j) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) {
throw out_of_range("Vertex does not exist");
}
// An undirected graph has a symmetric adjacency matrix: (i, j) == (j, i)
adjMat[i][j] = 1;
adjMat[j][i] = 1;
}
/* Remove an edge */
// Parameters i and j are indices into vertices
void removeEdge(int i, int j) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) {
throw out_of_range("Vertex does not exist");
}
adjMat[i][j] = 0;
adjMat[j][i] = 0;
}
/* Print the adjacency matrix */
void print() {
cout << "Vertex list = ";
printVector(vertices);
cout << "Adjacency matrix =" << endl;
printVectorMatrix(adjMat);
}
};
/* Undirected graph represented by an adjacency matrix */
class GraphAdjMat {
List<Integer> vertices; // Vertex list: each element holds a vertex value, and its position is the vertex index
List<List<Integer>> adjMat; // Adjacency matrix: row and column indices are vertex indices
/* Constructor */
public GraphAdjMat(int[] vertices, int[][] edges) {
this.vertices = new ArrayList<>();
this.adjMat = new ArrayList<>();
// Add a vertex
for (int val : vertices) {
addVertex(val);
}
// Add an edge
// The entries in edges are vertex indices, that is, indices into vertices
for (int[] e : edges) {
addEdge(e[0], e[1]);
}
}
/* Get the vertex count */
public int size() {
return vertices.size();
}
/* Add a vertex */
public void addVertex(int val) {
int n = size();
// Append the new vertex value to the vertex list
vertices.add(val);
// Add a row to the adjacency matrix
List<Integer> newRow = new ArrayList<>(n);
for (int j = 0; j < n; j++) {
newRow.add(0);
}
adjMat.add(newRow);
// Add a column to the adjacency matrix
for (List<Integer> row : adjMat) {
row.add(0);
}
}
/* Remove a vertex */
public void removeVertex(int index) {
if (index >= size())
throw new IndexOutOfBoundsException();
// Remove the vertex at the specified index from the vertex list
vertices.remove(index);
// Remove the row at the specified index from the adjacency matrix
adjMat.remove(index);
// Remove the column at the specified index from the adjacency matrix
for (List<Integer> row : adjMat) {
row.remove(index);
}
}
/* Add an edge */
// Parameters i and j are indices into vertices
public void addEdge(int i, int j) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j)
throw new IndexOutOfBoundsException();
// An undirected graph has a symmetric adjacency matrix: (i, j) == (j, i)
adjMat.get(i).set(j, 1);
adjMat.get(j).set(i, 1);
}
/* Remove an edge */
// Parameters i and j are indices into vertices
public void removeEdge(int i, int j) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j)
throw new IndexOutOfBoundsException();
adjMat.get(i).set(j, 0);
adjMat.get(j).set(i, 0);
}
/* Print the adjacency matrix */
public void print() {
System.out.print("Vertex list = ");
System.out.println(vertices);
System.out.println("Adjacency matrix =");
PrintUtil.printMatrix(adjMat);
}
}
/* Undirected graph represented by an adjacency matrix */
class GraphAdjMat {
List<int> vertices; // Vertex list: each element holds a vertex value, and its position is the vertex index
List<List<int>> adjMat; // Adjacency matrix: row and column indices are vertex indices
/* Constructor */
public GraphAdjMat(int[] vertices, int[][] edges) {
this.vertices = [];
this.adjMat = [];
// Add a vertex
foreach (int val in vertices) {
AddVertex(val);
}
// Add an edge
// The entries in edges are vertex indices, that is, indices into vertices
foreach (int[] e in edges) {
AddEdge(e[0], e[1]);
}
}
/* Get the vertex count */
int Size() {
return vertices.Count;
}
/* Add a vertex */
public void AddVertex(int val) {
int n = Size();
// Append the new vertex value to the vertex list
vertices.Add(val);
// Add a row to the adjacency matrix
List<int> newRow = new(n);
for (int j = 0; j < n; j++) {
newRow.Add(0);
}
adjMat.Add(newRow);
// Add a column to the adjacency matrix
foreach (List<int> row in adjMat) {
row.Add(0);
}
}
/* Remove a vertex */
public void RemoveVertex(int index) {
if (index >= Size())
throw new IndexOutOfRangeException();
// Remove the vertex at the specified index from the vertex list
vertices.RemoveAt(index);
// Remove the row at the specified index from the adjacency matrix
adjMat.RemoveAt(index);
// Remove the column at the specified index from the adjacency matrix
foreach (List<int> row in adjMat) {
row.RemoveAt(index);
}
}
/* Add an edge */
// Parameters i and j are indices into vertices
public void AddEdge(int i, int j) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= Size() || j >= Size() || i == j)
throw new IndexOutOfRangeException();
// An undirected graph has a symmetric adjacency matrix: (i, j) == (j, i)
adjMat[i][j] = 1;
adjMat[j][i] = 1;
}
/* Remove an edge */
// Parameters i and j are indices into vertices
public void RemoveEdge(int i, int j) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= Size() || j >= Size() || i == j)
throw new IndexOutOfRangeException();
adjMat[i][j] = 0;
adjMat[j][i] = 0;
}
/* Print the adjacency matrix */
public void Print() {
Console.Write("Vertex list = ");
PrintUtil.PrintList(vertices);
Console.WriteLine("Adjacency matrix =");
PrintUtil.PrintMatrix(adjMat);
}
}
/* Undirected graph represented by an adjacency matrix */
type graphAdjMat struct {
// Vertex list: each element holds a vertex value, and its position is the vertex index
vertices []int
// Adjacency matrix: row and column indices are vertex indices
adjMat [][]int
}
/* Constructor */
func newGraphAdjMat(vertices []int, edges [][]int) *graphAdjMat {
// Add a vertex
n := len(vertices)
adjMat := make([][]int, n)
for i := range adjMat {
adjMat[i] = make([]int, n)
}
// Initialize the graph
g := &graphAdjMat{
vertices: vertices,
adjMat: adjMat,
}
// Add an edge
// The entries in edges are vertex indices, that is, indices into vertices
for i := range edges {
g.addEdge(edges[i][0], edges[i][1])
}
return g
}
/* Get the vertex count */
func (g *graphAdjMat) size() int {
return len(g.vertices)
}
/* Add a vertex */
func (g *graphAdjMat) addVertex(val int) {
n := g.size()
// Append the new vertex value to the vertex list
g.vertices = append(g.vertices, val)
// Add a row to the adjacency matrix
newRow := make([]int, n)
g.adjMat = append(g.adjMat, newRow)
// Add a column to the adjacency matrix
for i := range g.adjMat {
g.adjMat[i] = append(g.adjMat[i], 0)
}
}
/* Remove a vertex */
func (g *graphAdjMat) removeVertex(index int) {
if index >= g.size() {
return
}
// Remove the vertex at the specified index from the vertex list
g.vertices = append(g.vertices[:index], g.vertices[index+1:]...)
// Remove the row at the specified index from the adjacency matrix
g.adjMat = append(g.adjMat[:index], g.adjMat[index+1:]...)
// Remove the column at the specified index from the adjacency matrix
for i := range g.adjMat {
g.adjMat[i] = append(g.adjMat[i][:index], g.adjMat[i][index+1:]...)
}
}
/* Add an edge */
// Parameters i and j are indices into vertices
func (g *graphAdjMat) addEdge(i, j int) {
// Check for out-of-bounds or equal indices
if i < 0 || j < 0 || i >= g.size() || j >= g.size() || i == j {
fmt.Errorf("%s", "Index Out Of Bounds Exception")
}
// An undirected graph has a symmetric adjacency matrix: (i, j) == (j, i)
g.adjMat[i][j] = 1
g.adjMat[j][i] = 1
}
/* Remove an edge */
// Parameters i and j are indices into vertices
func (g *graphAdjMat) removeEdge(i, j int) {
// Check for out-of-bounds or equal indices
if i < 0 || j < 0 || i >= g.size() || j >= g.size() || i == j {
fmt.Errorf("%s", "Index Out Of Bounds Exception")
}
g.adjMat[i][j] = 0
g.adjMat[j][i] = 0
}
/* Print the adjacency matrix */
func (g *graphAdjMat) print() {
fmt.Printf("\tVertex list = %v\n", g.vertices)
fmt.Printf("\tAdjacency matrix = \n")
for i := range g.adjMat {
fmt.Printf("\t\t\t%v\n", g.adjMat[i])
}
}
/* Undirected graph represented by an adjacency matrix */
class GraphAdjMat {
private var vertices: [Int] // Vertex list: each element holds a vertex value, and its position is the vertex index
private var adjMat: [[Int]] // Adjacency matrix: row and column indices are vertex indices
/* Constructor */
init(vertices: [Int], edges: [[Int]]) {
self.vertices = []
adjMat = []
// Add a vertex
for val in vertices {
addVertex(val: val)
}
// Add an edge
// The entries in edges are vertex indices, that is, indices into vertices
for e in edges {
addEdge(i: e[0], j: e[1])
}
}
/* Get the vertex count */
func size() -> Int {
vertices.count
}
/* Add a vertex */
func addVertex(val: Int) {
let n = size()
// Append the new vertex value to the vertex list
vertices.append(val)
// Add a row to the adjacency matrix
let newRow = Array(repeating: 0, count: n)
adjMat.append(newRow)
// Add a column to the adjacency matrix
for i in adjMat.indices {
adjMat[i].append(0)
}
}
/* Remove a vertex */
func removeVertex(index: Int) {
if index >= size() {
fatalError("Index out of bounds")
}
// Remove the vertex at the specified index from the vertex list
vertices.remove(at: index)
// Remove the row at the specified index from the adjacency matrix
adjMat.remove(at: index)
// Remove the column at the specified index from the adjacency matrix
for i in adjMat.indices {
adjMat[i].remove(at: index)
}
}
/* Add an edge */
// Parameters i and j are indices into vertices
func addEdge(i: Int, j: Int) {
// Check for out-of-bounds or equal indices
if i < 0 || j < 0 || i >= size() || j >= size() || i == j {
fatalError("Index out of bounds")
}
// An undirected graph has a symmetric adjacency matrix: (i, j) == (j, i)
adjMat[i][j] = 1
adjMat[j][i] = 1
}
/* Remove an edge */
// Parameters i and j are indices into vertices
func removeEdge(i: Int, j: Int) {
// Check for out-of-bounds or equal indices
if i < 0 || j < 0 || i >= size() || j >= size() || i == j {
fatalError("Index out of bounds")
}
adjMat[i][j] = 0
adjMat[j][i] = 0
}
/* Print the adjacency matrix */
func print() {
Swift.print("Vertex list = ", terminator: "")
Swift.print(vertices)
Swift.print("Adjacency matrix =")
PrintUtil.printMatrix(matrix: adjMat)
}
}
/* Undirected graph represented by an adjacency matrix */
class GraphAdjMat {
vertices; // Vertex list: each element holds a vertex value, and its position is the vertex index
adjMat; // Adjacency matrix: row and column indices are vertex indices
/* Constructor */
constructor(vertices, edges) {
this.vertices = [];
this.adjMat = [];
// Add a vertex
for (const val of vertices) {
this.addVertex(val);
}
// Add an edge
// The entries in edges are vertex indices, that is, indices into vertices
for (const e of edges) {
this.addEdge(e[0], e[1]);
}
}
/* Get the vertex count */
size() {
return this.vertices.length;
}
/* Add a vertex */
addVertex(val) {
const n = this.size();
// Append the new vertex value to the vertex list
this.vertices.push(val);
// Add a row to the adjacency matrix
const newRow = [];
for (let j = 0; j < n; j++) {
newRow.push(0);
}
this.adjMat.push(newRow);
// Add a column to the adjacency matrix
for (const row of this.adjMat) {
row.push(0);
}
}
/* Remove a vertex */
removeVertex(index) {
if (index >= this.size()) {
throw new RangeError('Index Out Of Bounds Exception');
}
// Remove the vertex at the specified index from the vertex list
this.vertices.splice(index, 1);
// Remove the row at the specified index from the adjacency matrix
this.adjMat.splice(index, 1);
// Remove the column at the specified index from the adjacency matrix
for (const row of this.adjMat) {
row.splice(index, 1);
}
}
/* Add an edge */
// Parameters i and j are indices into vertices
addEdge(i, j) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
throw new RangeError('Index Out Of Bounds Exception');
}
// An undirected graph has a symmetric adjacency matrix: (i, j) === (j, i)
this.adjMat[i][j] = 1;
this.adjMat[j][i] = 1;
}
/* Remove an edge */
// Parameters i and j are indices into vertices
removeEdge(i, j) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
throw new RangeError('Index Out Of Bounds Exception');
}
this.adjMat[i][j] = 0;
this.adjMat[j][i] = 0;
}
/* Print the adjacency matrix */
print() {
console.log('Vertex list = ', this.vertices);
console.log('Adjacency matrix =', this.adjMat);
}
}
/* Undirected graph represented by an adjacency matrix */
class GraphAdjMat {
vertices: number[]; // Vertex list: each element holds a vertex value, and its position is the vertex index
adjMat: number[][]; // Adjacency matrix: row and column indices are vertex indices
/* Constructor */
constructor(vertices: number[], edges: number[][]) {
this.vertices = [];
this.adjMat = [];
// Add a vertex
for (const val of vertices) {
this.addVertex(val);
}
// Add an edge
// The entries in edges are vertex indices, that is, indices into vertices
for (const e of edges) {
this.addEdge(e[0], e[1]);
}
}
/* Get the vertex count */
size(): number {
return this.vertices.length;
}
/* Add a vertex */
addVertex(val: number): void {
const n: number = this.size();
// Append the new vertex value to the vertex list
this.vertices.push(val);
// Add a row to the adjacency matrix
const newRow: number[] = [];
for (let j: number = 0; j < n; j++) {
newRow.push(0);
}
this.adjMat.push(newRow);
// Add a column to the adjacency matrix
for (const row of this.adjMat) {
row.push(0);
}
}
/* Remove a vertex */
removeVertex(index: number): void {
if (index >= this.size()) {
throw new RangeError('Index Out Of Bounds Exception');
}
// Remove the vertex at the specified index from the vertex list
this.vertices.splice(index, 1);
// Remove the row at the specified index from the adjacency matrix
this.adjMat.splice(index, 1);
// Remove the column at the specified index from the adjacency matrix
for (const row of this.adjMat) {
row.splice(index, 1);
}
}
/* Add an edge */
// Parameters i and j are indices into vertices
addEdge(i: number, j: number): void {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
throw new RangeError('Index Out Of Bounds Exception');
}
// An undirected graph has a symmetric adjacency matrix: (i, j) === (j, i)
this.adjMat[i][j] = 1;
this.adjMat[j][i] = 1;
}
/* Remove an edge */
// Parameters i and j are indices into vertices
removeEdge(i: number, j: number): void {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
throw new RangeError('Index Out Of Bounds Exception');
}
this.adjMat[i][j] = 0;
this.adjMat[j][i] = 0;
}
/* Print the adjacency matrix */
print(): void {
console.log('Vertex list = ', this.vertices);
console.log('Adjacency matrix =', this.adjMat);
}
}
/* Undirected graph represented by an adjacency matrix */
class GraphAdjMat {
List<int> vertices = []; // Vertex entries: each value is a vertex value, and its position is the vertex index
List<List<int>> adjMat = []; //Adjacency matrix: row and column indices are vertex indices
/* Constructor */
GraphAdjMat(List<int> vertices, List<List<int>> edges) {
this.vertices = [];
this.adjMat = [];
// Add a vertex
for (int val in vertices) {
addVertex(val);
}
// Add an edge
// The entries in edges are vertex indices, that is, indices into vertices
for (List<int> e in edges) {
addEdge(e[0], e[1]);
}
}
/* Get the vertex count */
int size() {
return vertices.length;
}
/* Add a vertex */
void addVertex(int val) {
int n = size();
// Append the new vertex value to the vertex list
vertices.add(val);
// Add a row to the adjacency matrix
List<int> newRow = List.filled(n, 0, growable: true);
adjMat.add(newRow);
// Add a column to the adjacency matrix
for (List<int> row in adjMat) {
row.add(0);
}
}
/* Remove a vertex */
void removeVertex(int index) {
if (index >= size()) {
throw IndexError;
}
// Remove the vertex at the specified index from the vertex list
vertices.removeAt(index);
// Remove the row at the specified index from the adjacency matrix
adjMat.removeAt(index);
// Remove the column at the specified index from the adjacency matrix
for (List<int> row in adjMat) {
row.removeAt(index);
}
}
/* Add an edge */
// Parameters i and j are indices into vertices
void addEdge(int i, int j) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) {
throw IndexError;
}
// An undirected graph has a symmetric adjacency matrix: (i, j) == (j, i)
adjMat[i][j] = 1;
adjMat[j][i] = 1;
}
/* Remove an edge */
// Parameters i and j are indices into vertices
void removeEdge(int i, int j) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) {
throw IndexError;
}
adjMat[i][j] = 0;
adjMat[j][i] = 0;
}
/* Print the adjacency matrix */
void printAdjMat() {
print("Vertex list = $vertices");
print("Adjacency matrix = ");
printMatrix(adjMat);
}
}
/* Undirected graph type represented by an adjacency matrix */
pub struct GraphAdjMat {
// Vertex list: each element holds a vertex value, and its position is the vertex index
pub vertices: Vec<i32>,
// Adjacency matrix: row and column indices are vertex indices
pub adj_mat: Vec<Vec<i32>>,
}
impl GraphAdjMat {
/* Constructor */
pub fn new(vertices: Vec<i32>, edges: Vec<[usize; 2]>) -> Self {
let mut graph = GraphAdjMat {
vertices: vec![],
adj_mat: vec![],
};
// Add a vertex
for val in vertices {
graph.add_vertex(val);
}
// Add an edge
// The entries in edges are vertex indices, that is, indices into vertices
for edge in edges {
graph.add_edge(edge[0], edge[1])
}
graph
}
/* Get the vertex count */
pub fn size(&self) -> usize {
self.vertices.len()
}
/* Add a vertex */
pub fn add_vertex(&mut self, val: i32) {
let n = self.size();
// Append the new vertex value to the vertex list
self.vertices.push(val);
// Add a row to the adjacency matrix
self.adj_mat.push(vec![0; n]);
// Add a column to the adjacency matrix
for row in self.adj_mat.iter_mut() {
row.push(0);
}
}
/* Remove a vertex */
pub fn remove_vertex(&mut self, index: usize) {
if index >= self.size() {
panic!("index error")
}
// Remove the vertex at the specified index from the vertex list
self.vertices.remove(index);
// Remove the row at the specified index from the adjacency matrix
self.adj_mat.remove(index);
// Remove the column at the specified index from the adjacency matrix
for row in self.adj_mat.iter_mut() {
row.remove(index);
}
}
/* Add an edge */
pub fn add_edge(&mut self, i: usize, j: usize) {
// Parameters i and j are indices into vertices
// Check for out-of-bounds or equal indices
if i >= self.size() || j >= self.size() || i == j {
panic!("index error")
}
// An undirected graph has a symmetric adjacency matrix: (i, j) == (j, i)
self.adj_mat[i][j] = 1;
self.adj_mat[j][i] = 1;
}
/* Remove an edge */
// Parameters i and j are indices into vertices
pub fn remove_edge(&mut self, i: usize, j: usize) {
// Parameters i and j are indices into vertices
// Check for out-of-bounds or equal indices
if i >= self.size() || j >= self.size() || i == j {
panic!("index error")
}
self.adj_mat[i][j] = 0;
self.adj_mat[j][i] = 0;
}
/* Print the adjacency matrix */
pub fn print(&self) {
println!("Vertex list = {:?}", self.vertices);
println!("Adjacency matrix =");
println!("[");
for row in &self.adj_mat {
println!(" {:?},", row);
}
println!("]")
}
}
/* Structure for an undirected graph represented by an adjacency matrix */
typedef struct {
int vertices[MAX_SIZE];
int adjMat[MAX_SIZE][MAX_SIZE];
int size;
} GraphAdjMat;
/* Constructor */
GraphAdjMat *newGraphAdjMat() {
GraphAdjMat *graph = (GraphAdjMat *)malloc(sizeof(GraphAdjMat));
graph->size = 0;
for (int i = 0; i < MAX_SIZE; i++) {
for (int j = 0; j < MAX_SIZE; j++) {
graph->adjMat[i][j] = 0;
}
}
return graph;
}
/* Destructor */
void delGraphAdjMat(GraphAdjMat *graph) {
free(graph);
}
/* Add a vertex */
void addVertex(GraphAdjMat *graph, int val) {
if (graph->size == MAX_SIZE) {
fprintf(stderr, "The graph has reached its maximum number of vertices\n");
return;
}
// Add the nth vertex and set row n and column n to zero
int n = graph->size;
graph->vertices[n] = val;
for (int i = 0; i <= n; i++) {
graph->adjMat[n][i] = graph->adjMat[i][n] = 0;
}
graph->size++;
}
/* Remove a vertex */
void removeVertex(GraphAdjMat *graph, int index) {
if (index < 0 || index >= graph->size) {
fprintf(stderr, "Vertex index out of bounds\n");
return;
}
// Remove the vertex at the specified index from the vertex list
for (int i = index; i < graph->size - 1; i++) {
graph->vertices[i] = graph->vertices[i + 1];
}
// Remove the row at the specified index from the adjacency matrix
for (int i = index; i < graph->size - 1; i++) {
for (int j = 0; j < graph->size; j++) {
graph->adjMat[i][j] = graph->adjMat[i + 1][j];
}
}
// Remove the column at the specified index from the adjacency matrix
for (int i = 0; i < graph->size; i++) {
for (int j = index; j < graph->size - 1; j++) {
graph->adjMat[i][j] = graph->adjMat[i][j + 1];
}
}
graph->size--;
}
/* Add an edge */
// Parameters i and j are indices into vertices
void addEdge(GraphAdjMat *graph, int i, int j) {
if (i < 0 || j < 0 || i >= graph->size || j >= graph->size || i == j) {
fprintf(stderr, "Edge endpoint indices are out of bounds or equal\n");
return;
}
graph->adjMat[i][j] = 1;
graph->adjMat[j][i] = 1;
}
/* Remove an edge */
// Parameters i and j are indices into vertices
void removeEdge(GraphAdjMat *graph, int i, int j) {
if (i < 0 || j < 0 || i >= graph->size || j >= graph->size || i == j) {
fprintf(stderr, "Edge endpoint indices are out of bounds or equal\n");
return;
}
graph->adjMat[i][j] = 0;
graph->adjMat[j][i] = 0;
}
/* Print the adjacency matrix */
void printGraphAdjMat(GraphAdjMat *graph) {
printf("Vertex list = ");
printArray(graph->vertices, graph->size);
printf("Adjacency matrix =\n");
for (int i = 0; i < graph->size; i++) {
printArray(graph->adjMat[i], graph->size);
}
}
/* Undirected graph represented by an adjacency matrix */
class GraphAdjMat(vertices: IntArray, edges: Array<IntArray>) {
val vertices = mutableListOf<Int>() // Vertex list: each element holds a vertex value, and its position is the vertex index
val adjMat = mutableListOf<MutableList<Int>>() // Adjacency matrix: row and column indices are vertex indices
/* Constructor */
init {
// Add a vertex
for (vertex in vertices) {
addVertex(vertex)
}
// Add an edge
// The entries in edges are vertex indices, that is, indices into vertices
for (edge in edges) {
addEdge(edge[0], edge[1])
}
}
/* Get the vertex count */
fun size(): Int {
return vertices.size
}
/* Add a vertex */
fun addVertex(_val: Int) {
val n = size()
// Append the new vertex value to the vertex list
vertices.add(_val)
// Add a row to the adjacency matrix
val newRow = mutableListOf<Int>()
for (j in 0..<n) {
newRow.add(0)
}
adjMat.add(newRow)
// Add a column to the adjacency matrix
for (row in adjMat) {
row.add(0)
}
}
/* Remove a vertex */
fun removeVertex(index: Int) {
if (index >= size())
throw IndexOutOfBoundsException()
// Remove the vertex at the specified index from the vertex list
vertices.removeAt(index)
// Remove the row at the specified index from the adjacency matrix
adjMat.removeAt(index)
// Remove the column at the specified index from the adjacency matrix
for (row in adjMat) {
row.removeAt(index)
}
}
/* Add an edge */
// Parameters i and j are indices into vertices
fun addEdge(i: Int, j: Int) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j)
throw IndexOutOfBoundsException()
// An undirected graph has a symmetric adjacency matrix: (i, j) == (j, i)
adjMat[i][j] = 1
adjMat[j][i] = 1
}
/* Remove an edge */
// Parameters i and j are indices into vertices
fun removeEdge(i: Int, j: Int) {
// Check for out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j)
throw IndexOutOfBoundsException()
adjMat[i][j] = 0
adjMat[j][i] = 0
}
/* Print the adjacency matrix */
fun print() {
print("Vertex list = ")
println(vertices)
println("Adjacency matrix =")
printMatrix(adjMat)
}
}
### Undirected graph represented by an adjacency matrix ###
class GraphAdjMat
def initialize(vertices, edges)
### Constructor ###
# Vertex list: each element holds a vertex value, and its position is the vertex index
@vertices = []
# Adjacency matrix: row and column indices are vertex indices
@adj_mat = []
# Add a vertex
vertices.each { |val| add_vertex(val) }
# Add an edge
# The entries in edges are vertex indices, that is, indices into vertices
edges.each { |e| add_edge(e[0], e[1]) }
end
### Get the vertex count ###
def size
@vertices.length
end
### Add a vertex ###
def add_vertex(val)
n = size
# Append the new vertex value to the vertex list
@vertices << val
# Add a row to the adjacency matrix
new_row = Array.new(n, 0)
@adj_mat << new_row
# Add a column to the adjacency matrix
@adj_mat.each { |row| row << 0 }
end
### Remove a vertex ###
def remove_vertex(index)
raise IndexError if index >= size
# Remove the vertex at the specified index from the vertex list
@vertices.delete_at(index)
# Remove the row at the specified index from the adjacency matrix
@adj_mat.delete_at(index)
# Remove the column at the specified index from the adjacency matrix
@adj_mat.each { |row| row.delete_at(index) }
end
### Add an edge ###
def add_edge(i, j)
# Parameters i and j are indices into vertices
# Check for out-of-bounds or equal indices
if i < 0 || j < 0 || i >= size || j >= size || i == j
raise IndexError
end
# An undirected graph has a symmetric adjacency matrix: (i, j) == (j, i)
@adj_mat[i][j] = 1
@adj_mat[j][i] = 1
end
### Remove an edge ###
def remove_edge(i, j)
# Parameters i and j are indices into vertices
# Check for out-of-bounds or equal indices
if i < 0 || j < 0 || i >= size || j >= size || i == j
raise IndexError
end
@adj_mat[i][j] = 0
@adj_mat[j][i] = 0
end
### Print the adjacency matrix ###
def __print__
puts "Vertex list = #{@vertices}"
puts 'Adjacency matrix ='
print_matrix(@adj_mat)
end
end
Visualize execution
9.2.2 Adjacency list implementation¶
For an undirected graph with \(n\) vertices and \(m\) edges, we can implement each operation as shown below.
- Add an edge: Append the edge to the list for each endpoint in \(O(1)\) time. Since the graph is undirected, add entries in both directions.
- Remove an edge: Find and remove the specified edge in the corresponding lists in \(O(m)\) time. In an undirected graph, remove the entries for both directions.
- Add a vertex: Add a linked list to the adjacency list, using the new vertex as its head. This takes \(O(1)\) time.
- Remove a vertex: Traverse the entire adjacency list and remove every edge incident to the vertex. This takes \(O(n + m)\) time.
- Initialize: Create \(n\) vertices and \(2m\) edges in the adjacency list in \(O(n + m)\) time.
Figure 9-8 Initializing an adjacency list and adding or removing edges and vertices
Description of Figure 9-8: Adding and removing edges and vertices in an adjacency list
Follow changes to the rows and their neighbors as edges and vertices are added to or removed from an adjacency list.
The head nodes in the left column represent vertices. Arrows pointing right in each row are references in a linked list of neighbors. They do not indicate directed edges in the original graph. At each step, the table gives the complete neighbor lists in the order shown. A vertex retains its identity even if its row changes position.
An undirected edge appears in both endpoints' lists, so adding or removing an edge requires updating both rows. To add an isolated vertex, add an empty list. To remove a vertex, remove its entire row and scan the remaining lists to delete entries for that vertex.
The figure inserts each new neighbor at the head of the list. The lists earlier in the text and the code append new neighbors at the end (the code uses dynamic arrays in place of linked lists). Both orders represent the same undirected connections.
Initialize the five-vertex graph
The vertices are initially ordered [1, 3, 2, 5, 4]. There are 6 undirected edges: 1—3, 1—5, 2—3, 2—5, 2—4, and 4—5. There is no edge 1—2 yet. Each table row lists the neighbors of one vertex.
Adjacency list, step 1: complete initial state Vertex Neighbors in the order shown 1 3, 5 3 1, 2 2 3, 5, 4 5 1, 2, 4 4 2, 5 Add edge 1—2
Add undirected edge 1—2 by inserting 2 at the head of the list for vertex 1 and 1 at the head of the list for vertex 2. The other rows stay the same. There are still 5 vertices, and the edge count rises to 7. The table gives both updated lists in full.
Adjacency list, step 2: complete state after adding edge 1—2 Vertex Neighbors in the order shown 1 2, 3, 5 3 1, 2 2 1, 3, 5, 4 5 1, 2, 4 4 2, 5 Remove edge 1—3
Remove undirected edge 1—3 by deleting 3 from the list for vertex 1 and 1 from the list for vertex 3. The graph still has 5 vertices and now has 6 edges. The neighbors of 1 are 2 and 5, and 3 is connected only to 2.
Adjacency list, step 3: complete state after removing edge 1—3 Vertex Neighbors in the order shown 1 2, 5 3 2 2 1, 3, 5, 4 5 1, 2, 4 4 2, 5 Add isolated vertex 6
Append an empty list for vertex 6. The rows are now ordered [1, 3, 2, 5, 4, 6]. All other rows stay the same. There are still 6 edges, and vertex 6 is isolated.
Adjacency list, step 4: complete state after adding isolated vertex 6 Vertex Neighbors in the order shown 1 2, 5 3 2 2 1, 3, 5, 4 5 1, 2, 4 4 2, 5 6 Empty Remove vertex 3
Remove the entire row for vertex 3, then scan the remaining lists for entries pointing to 3. Edge 1—3 was removed in step 3, so only vertex 2 is still connected to 3. Delete 3 from its list. The remaining vertices are ordered [1, 2, 5, 4, 6]. Moving rows up does not rename the vertices. The neighbors of 2 are 1, 5, and 4. Vertex 6 is still isolated, and there are 5 edges.
Adjacency list, step 5: complete state after removing vertex 3 Vertex Neighbors in the order shown 1 2, 5 2 1, 5, 4 5 1, 2, 4 4 2, 5 6 Empty
The following code implements an adjacency list. It differs from Figure 9-8 in two ways.
- To simplify the code and make vertices easy to add and remove, we use lists (dynamic arrays) in place of linked lists.
- We store the adjacency list in a hash table. Each
keyis a vertex instance, and itsvalueis the list of adjacent vertices (the linked list in the figure).
We also use the Vertex class to represent vertices in the adjacency list. Suppose we identified vertices by list index, as we did in the adjacency matrix. Removing the vertex at index \(i\) would require scanning the entire adjacency list and decreasing every index greater than \(i\) by \(1\), which is inefficient. When each vertex is a distinct Vertex instance, removing one vertex leaves the identities of all others unchanged.
class GraphAdjList:
"""Undirected graph represented by an adjacency list"""
def __init__(self, edges: list[list[Vertex]]):
"""Constructor"""
# Adjacency list: each vertex maps to its neighbors
self.adj_list = dict[Vertex, list[Vertex]]()
# Add all vertices and edges
for edge in edges:
self.add_vertex(edge[0])
self.add_vertex(edge[1])
self.add_edge(edge[0], edge[1])
def size(self) -> int:
"""Get the vertex count"""
return len(self.adj_list)
def add_edge(self, vet1: Vertex, vet2: Vertex):
"""Add an edge"""
if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2:
raise ValueError()
# Add the edge vet1 - vet2
self.adj_list[vet1].append(vet2)
self.adj_list[vet2].append(vet1)
def remove_edge(self, vet1: Vertex, vet2: Vertex):
"""Remove an edge"""
if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2:
raise ValueError()
# Remove the edge vet1 - vet2
self.adj_list[vet1].remove(vet2)
self.adj_list[vet2].remove(vet1)
def add_vertex(self, vet: Vertex):
"""Add a vertex"""
if vet in self.adj_list:
return
# Add a new linked list to the adjacency list
self.adj_list[vet] = []
def remove_vertex(self, vet: Vertex):
"""Remove a vertex"""
if vet not in self.adj_list:
raise ValueError()
# Remove the linked list for vertex vet from the adjacency list
self.adj_list.pop(vet)
# Traverse the other vertices' lists and remove every edge incident to vet
for vertex in self.adj_list:
if vet in self.adj_list[vertex]:
self.adj_list[vertex].remove(vet)
def print(self):
"""Print the adjacency list"""
print("Adjacency list =")
for vertex in self.adj_list:
tmp = [v.val for v in self.adj_list[vertex]]
print(f"{vertex.val}: {tmp},")
/* Undirected graph represented by an adjacency list */
class GraphAdjList {
public:
// Adjacency list: each vertex maps to its neighbors
unordered_map<Vertex *, vector<Vertex *>> adjList;
/* Remove the specified node from the vector */
void remove(vector<Vertex *> &vec, Vertex *vet) {
for (int i = 0; i < vec.size(); i++) {
if (vec[i] == vet) {
vec.erase(vec.begin() + i);
break;
}
}
}
/* Constructor */
GraphAdjList(const vector<vector<Vertex *>> &edges) {
// Add all vertices and edges
for (const vector<Vertex *> &edge : edges) {
addVertex(edge[0]);
addVertex(edge[1]);
addEdge(edge[0], edge[1]);
}
}
/* Get the vertex count */
int size() {
return adjList.size();
}
/* Add an edge */
void addEdge(Vertex *vet1, Vertex *vet2) {
if (!adjList.count(vet1) || !adjList.count(vet2) || vet1 == vet2)
throw invalid_argument("Vertex does not exist");
// Add the edge vet1 - vet2
adjList[vet1].push_back(vet2);
adjList[vet2].push_back(vet1);
}
/* Remove an edge */
void removeEdge(Vertex *vet1, Vertex *vet2) {
if (!adjList.count(vet1) || !adjList.count(vet2) || vet1 == vet2)
throw invalid_argument("Vertex does not exist");
// Remove the edge vet1 - vet2
remove(adjList[vet1], vet2);
remove(adjList[vet2], vet1);
}
/* Add a vertex */
void addVertex(Vertex *vet) {
if (adjList.count(vet))
return;
// Add a new linked list to the adjacency list
adjList[vet] = vector<Vertex *>();
}
/* Remove a vertex */
void removeVertex(Vertex *vet) {
if (!adjList.count(vet))
throw invalid_argument("Vertex does not exist");
// Remove the linked list for vertex vet from the adjacency list
adjList.erase(vet);
// Traverse the other vertices' lists and remove every edge incident to vet
for (auto &adj : adjList) {
remove(adj.second, vet);
}
}
/* Print the adjacency list */
void print() {
cout << "Adjacency list =" << endl;
for (auto &adj : adjList) {
const auto &key = adj.first;
const auto &vec = adj.second;
cout << key->val << ": ";
printVector(vetsToVals(vec));
}
}
};
/* Undirected graph represented by an adjacency list */
class GraphAdjList {
// Adjacency list: each vertex maps to its neighbors
Map<Vertex, List<Vertex>> adjList;
/* Constructor */
public GraphAdjList(Vertex[][] edges) {
this.adjList = new HashMap<>();
// Add all vertices and edges
for (Vertex[] edge : edges) {
addVertex(edge[0]);
addVertex(edge[1]);
addEdge(edge[0], edge[1]);
}
}
/* Get the vertex count */
public int size() {
return adjList.size();
}
/* Add an edge */
public void addEdge(Vertex vet1, Vertex vet2) {
if (!adjList.containsKey(vet1) || !adjList.containsKey(vet2) || vet1 == vet2)
throw new IllegalArgumentException();
// Add the edge vet1 - vet2
adjList.get(vet1).add(vet2);
adjList.get(vet2).add(vet1);
}
/* Remove an edge */
public void removeEdge(Vertex vet1, Vertex vet2) {
if (!adjList.containsKey(vet1) || !adjList.containsKey(vet2) || vet1 == vet2)
throw new IllegalArgumentException();
// Remove the edge vet1 - vet2
adjList.get(vet1).remove(vet2);
adjList.get(vet2).remove(vet1);
}
/* Add a vertex */
public void addVertex(Vertex vet) {
if (adjList.containsKey(vet))
return;
// Add a new linked list to the adjacency list
adjList.put(vet, new ArrayList<>());
}
/* Remove a vertex */
public void removeVertex(Vertex vet) {
if (!adjList.containsKey(vet))
throw new IllegalArgumentException();
// Remove the linked list for vertex vet from the adjacency list
adjList.remove(vet);
// Traverse the other vertices' lists and remove every edge incident to vet
for (List<Vertex> list : adjList.values()) {
list.remove(vet);
}
}
/* Print the adjacency list */
public void print() {
System.out.println("Adjacency list =");
for (Map.Entry<Vertex, List<Vertex>> pair : adjList.entrySet()) {
List<Integer> tmp = new ArrayList<>();
for (Vertex vertex : pair.getValue())
tmp.add(vertex.val);
System.out.println(pair.getKey().val + ": " + tmp + ",");
}
}
}
/* Undirected graph represented by an adjacency list */
class GraphAdjList {
// Adjacency list: each vertex maps to its neighbors
public Dictionary<Vertex, List<Vertex>> adjList;
/* Constructor */
public GraphAdjList(Vertex[][] edges) {
adjList = [];
// Add all vertices and edges
foreach (Vertex[] edge in edges) {
AddVertex(edge[0]);
AddVertex(edge[1]);
AddEdge(edge[0], edge[1]);
}
}
/* Get the vertex count */
int Size() {
return adjList.Count;
}
/* Add an edge */
public void AddEdge(Vertex vet1, Vertex vet2) {
if (!adjList.ContainsKey(vet1) || !adjList.ContainsKey(vet2) || vet1 == vet2)
throw new InvalidOperationException();
// Add the edge vet1 - vet2
adjList[vet1].Add(vet2);
adjList[vet2].Add(vet1);
}
/* Remove an edge */
public void RemoveEdge(Vertex vet1, Vertex vet2) {
if (!adjList.ContainsKey(vet1) || !adjList.ContainsKey(vet2) || vet1 == vet2)
throw new InvalidOperationException();
// Remove the edge vet1 - vet2
adjList[vet1].Remove(vet2);
adjList[vet2].Remove(vet1);
}
/* Add a vertex */
public void AddVertex(Vertex vet) {
if (adjList.ContainsKey(vet))
return;
// Add a new linked list to the adjacency list
adjList.Add(vet, []);
}
/* Remove a vertex */
public void RemoveVertex(Vertex vet) {
if (!adjList.ContainsKey(vet))
throw new InvalidOperationException();
// Remove the linked list for vertex vet from the adjacency list
adjList.Remove(vet);
// Traverse the other vertices' lists and remove every edge incident to vet
foreach (List<Vertex> list in adjList.Values) {
list.Remove(vet);
}
}
/* Print the adjacency list */
public void Print() {
Console.WriteLine("Adjacency list =");
foreach (KeyValuePair<Vertex, List<Vertex>> pair in adjList) {
List<int> tmp = [];
foreach (Vertex vertex in pair.Value)
tmp.Add(vertex.val);
Console.WriteLine(pair.Key.val + ": [" + string.Join(", ", tmp) + "],");
}
}
}
/* Undirected graph represented by an adjacency list */
type graphAdjList struct {
// Adjacency list: each vertex maps to its neighbors
adjList map[Vertex][]Vertex
}
/* Constructor */
func newGraphAdjList(edges [][]Vertex) *graphAdjList {
g := &graphAdjList{
adjList: make(map[Vertex][]Vertex),
}
// Add all vertices and edges
for _, edge := range edges {
g.addVertex(edge[0])
g.addVertex(edge[1])
g.addEdge(edge[0], edge[1])
}
return g
}
/* Get the vertex count */
func (g *graphAdjList) size() int {
return len(g.adjList)
}
/* Add an edge */
func (g *graphAdjList) addEdge(vet1 Vertex, vet2 Vertex) {
_, ok1 := g.adjList[vet1]
_, ok2 := g.adjList[vet2]
if !ok1 || !ok2 || vet1 == vet2 {
panic("error")
}
// Add the edge vet1 - vet2 using an anonymous struct{}
g.adjList[vet1] = append(g.adjList[vet1], vet2)
g.adjList[vet2] = append(g.adjList[vet2], vet1)
}
/* Remove an edge */
func (g *graphAdjList) removeEdge(vet1 Vertex, vet2 Vertex) {
_, ok1 := g.adjList[vet1]
_, ok2 := g.adjList[vet2]
if !ok1 || !ok2 || vet1 == vet2 {
panic("error")
}
// Remove the edge vet1 - vet2
g.adjList[vet1] = DeleteSliceElms(g.adjList[vet1], vet2)
g.adjList[vet2] = DeleteSliceElms(g.adjList[vet2], vet1)
}
/* Add a vertex */
func (g *graphAdjList) addVertex(vet Vertex) {
_, ok := g.adjList[vet]
if ok {
return
}
// Add a new linked list to the adjacency list
g.adjList[vet] = make([]Vertex, 0)
}
/* Remove a vertex */
func (g *graphAdjList) removeVertex(vet Vertex) {
_, ok := g.adjList[vet]
if !ok {
panic("error")
}
// Remove the linked list for vertex vet from the adjacency list
delete(g.adjList, vet)
// Traverse the other vertices' lists and remove every edge incident to vet
for v, list := range g.adjList {
g.adjList[v] = DeleteSliceElms(list, vet)
}
}
/* Print the adjacency list */
func (g *graphAdjList) print() {
var builder strings.Builder
fmt.Printf("Adjacency list = \n")
for k, v := range g.adjList {
builder.WriteString("\t\t" + strconv.Itoa(k.Val) + ": ")
for _, vet := range v {
builder.WriteString(strconv.Itoa(vet.Val) + " ")
}
fmt.Println(builder.String())
builder.Reset()
}
}
/* Undirected graph represented by an adjacency list */
class GraphAdjList {
// Adjacency list: each vertex maps to its neighbors
public private(set) var adjList: [Vertex: [Vertex]]
/* Constructor */
public init(edges: [[Vertex]]) {
adjList = [:]
// Add all vertices and edges
for edge in edges {
addVertex(vet: edge[0])
addVertex(vet: edge[1])
addEdge(vet1: edge[0], vet2: edge[1])
}
}
/* Get the vertex count */
public func size() -> Int {
adjList.count
}
/* Add an edge */
public func addEdge(vet1: Vertex, vet2: Vertex) {
if adjList[vet1] == nil || adjList[vet2] == nil || vet1 == vet2 {
fatalError("Invalid argument")
}
// Add the edge vet1 - vet2
adjList[vet1]?.append(vet2)
adjList[vet2]?.append(vet1)
}
/* Remove an edge */
public func removeEdge(vet1: Vertex, vet2: Vertex) {
if adjList[vet1] == nil || adjList[vet2] == nil || vet1 == vet2 {
fatalError("Invalid argument")
}
// Remove the edge vet1 - vet2
adjList[vet1]?.removeAll { $0 == vet2 }
adjList[vet2]?.removeAll { $0 == vet1 }
}
/* Add a vertex */
public func addVertex(vet: Vertex) {
if adjList[vet] != nil {
return
}
// Add a new linked list to the adjacency list
adjList[vet] = []
}
/* Remove a vertex */
public func removeVertex(vet: Vertex) {
if adjList[vet] == nil {
fatalError("Invalid argument")
}
// Remove the linked list for vertex vet from the adjacency list
adjList.removeValue(forKey: vet)
// Traverse the other vertices' lists and remove every edge incident to vet
for key in adjList.keys {
adjList[key]?.removeAll { $0 == vet }
}
}
/* Print the adjacency list */
public func print() {
Swift.print("Adjacency list =")
for (vertex, list) in adjList {
let list = list.map { $0.val }
Swift.print("\(vertex.val): \(list),")
}
}
}
/* Undirected graph represented by an adjacency list */
class GraphAdjList {
// Adjacency list: each vertex maps to its neighbors
adjList;
/* Constructor */
constructor(edges) {
this.adjList = new Map();
// Add all vertices and edges
for (const edge of edges) {
this.addVertex(edge[0]);
this.addVertex(edge[1]);
this.addEdge(edge[0], edge[1]);
}
}
/* Get the vertex count */
size() {
return this.adjList.size;
}
/* Add an edge */
addEdge(vet1, vet2) {
if (
!this.adjList.has(vet1) ||
!this.adjList.has(vet2) ||
vet1 === vet2
) {
throw new Error('Illegal Argument Exception');
}
// Add the edge vet1 - vet2
this.adjList.get(vet1).push(vet2);
this.adjList.get(vet2).push(vet1);
}
/* Remove an edge */
removeEdge(vet1, vet2) {
if (
!this.adjList.has(vet1) ||
!this.adjList.has(vet2) ||
vet1 === vet2 ||
this.adjList.get(vet1).indexOf(vet2) === -1
) {
throw new Error('Illegal Argument Exception');
}
// Remove the edge vet1 - vet2
this.adjList.get(vet1).splice(this.adjList.get(vet1).indexOf(vet2), 1);
this.adjList.get(vet2).splice(this.adjList.get(vet2).indexOf(vet1), 1);
}
/* Add a vertex */
addVertex(vet) {
if (this.adjList.has(vet)) return;
// Add a new linked list to the adjacency list
this.adjList.set(vet, []);
}
/* Remove a vertex */
removeVertex(vet) {
if (!this.adjList.has(vet)) {
throw new Error('Illegal Argument Exception');
}
// Remove the linked list for vertex vet from the adjacency list
this.adjList.delete(vet);
// Traverse the other vertices' lists and remove every edge incident to vet
for (const set of this.adjList.values()) {
const index = set.indexOf(vet);
if (index > -1) {
set.splice(index, 1);
}
}
}
/* Print the adjacency list */
print() {
console.log('Adjacency list =');
for (const [key, value] of this.adjList) {
const tmp = [];
for (const vertex of value) {
tmp.push(vertex.val);
}
console.log(key.val + ': ' + tmp.join());
}
}
}
/* Undirected graph represented by an adjacency list */
class GraphAdjList {
// Adjacency list: each vertex maps to its neighbors
adjList: Map<Vertex, Vertex[]>;
/* Constructor */
constructor(edges: Vertex[][]) {
this.adjList = new Map();
// Add all vertices and edges
for (const edge of edges) {
this.addVertex(edge[0]);
this.addVertex(edge[1]);
this.addEdge(edge[0], edge[1]);
}
}
/* Get the vertex count */
size(): number {
return this.adjList.size;
}
/* Add an edge */
addEdge(vet1: Vertex, vet2: Vertex): void {
if (
!this.adjList.has(vet1) ||
!this.adjList.has(vet2) ||
vet1 === vet2
) {
throw new Error('Illegal Argument Exception');
}
// Add the edge vet1 - vet2
this.adjList.get(vet1).push(vet2);
this.adjList.get(vet2).push(vet1);
}
/* Remove an edge */
removeEdge(vet1: Vertex, vet2: Vertex): void {
if (
!this.adjList.has(vet1) ||
!this.adjList.has(vet2) ||
vet1 === vet2 ||
this.adjList.get(vet1).indexOf(vet2) === -1
) {
throw new Error('Illegal Argument Exception');
}
// Remove the edge vet1 - vet2
this.adjList.get(vet1).splice(this.adjList.get(vet1).indexOf(vet2), 1);
this.adjList.get(vet2).splice(this.adjList.get(vet2).indexOf(vet1), 1);
}
/* Add a vertex */
addVertex(vet: Vertex): void {
if (this.adjList.has(vet)) return;
// Add a new linked list to the adjacency list
this.adjList.set(vet, []);
}
/* Remove a vertex */
removeVertex(vet: Vertex): void {
if (!this.adjList.has(vet)) {
throw new Error('Illegal Argument Exception');
}
// Remove the linked list for vertex vet from the adjacency list
this.adjList.delete(vet);
// Traverse the other vertices' lists and remove every edge incident to vet
for (const set of this.adjList.values()) {
const index: number = set.indexOf(vet);
if (index > -1) {
set.splice(index, 1);
}
}
}
/* Print the adjacency list */
print(): void {
console.log('Adjacency list =');
for (const [key, value] of this.adjList.entries()) {
const tmp = [];
for (const vertex of value) {
tmp.push(vertex.val);
}
console.log(key.val + ': ' + tmp.join());
}
}
}
/* Undirected graph represented by an adjacency list */
class GraphAdjList {
// Adjacency list: each vertex maps to its neighbors
Map<Vertex, List<Vertex>> adjList = {};
/* Constructor */
GraphAdjList(List<List<Vertex>> edges) {
for (List<Vertex> edge in edges) {
addVertex(edge[0]);
addVertex(edge[1]);
addEdge(edge[0], edge[1]);
}
}
/* Get the vertex count */
int size() {
return adjList.length;
}
/* Add an edge */
void addEdge(Vertex vet1, Vertex vet2) {
if (!adjList.containsKey(vet1) ||
!adjList.containsKey(vet2) ||
vet1 == vet2) {
throw ArgumentError;
}
// Add the edge vet1 - vet2
adjList[vet1]!.add(vet2);
adjList[vet2]!.add(vet1);
}
/* Remove an edge */
void removeEdge(Vertex vet1, Vertex vet2) {
if (!adjList.containsKey(vet1) ||
!adjList.containsKey(vet2) ||
vet1 == vet2) {
throw ArgumentError;
}
// Remove the edge vet1 - vet2
adjList[vet1]!.remove(vet2);
adjList[vet2]!.remove(vet1);
}
/* Add a vertex */
void addVertex(Vertex vet) {
if (adjList.containsKey(vet)) return;
// Add a new linked list to the adjacency list
adjList[vet] = [];
}
/* Remove a vertex */
void removeVertex(Vertex vet) {
if (!adjList.containsKey(vet)) {
throw ArgumentError;
}
// Remove the linked list for vertex vet from the adjacency list
adjList.remove(vet);
// Traverse the other vertices' lists and remove every edge incident to vet
adjList.forEach((key, value) {
value.remove(vet);
});
}
/* Print the adjacency list */
void printAdjList() {
print("Adjacency list =");
adjList.forEach((key, value) {
List<int> tmp = [];
for (Vertex vertex in value) {
tmp.add(vertex.val);
}
print("${key.val}: $tmp,");
});
}
}
/* Undirected graph type represented by an adjacency list */
pub struct GraphAdjList {
// Adjacency list: each vertex maps to its neighbors
pub adj_list: HashMap<Vertex, Vec<Vertex>>, // Would HashSet<Vertex> be a better choice for the values?
}
impl GraphAdjList {
/* Constructor */
pub fn new(edges: Vec<[Vertex; 2]>) -> Self {
let mut graph = GraphAdjList {
adj_list: HashMap::new(),
};
// Add all vertices and edges
for edge in edges {
graph.add_vertex(edge[0]);
graph.add_vertex(edge[1]);
graph.add_edge(edge[0], edge[1]);
}
graph
}
/* Get the vertex count */
#[allow(unused)]
pub fn size(&self) -> usize {
self.adj_list.len()
}
/* Add an edge */
pub fn add_edge(&mut self, vet1: Vertex, vet2: Vertex) {
if vet1 == vet2 {
panic!("value error");
}
// Add the edge vet1 - vet2
self.adj_list.entry(vet1).or_default().push(vet2);
self.adj_list.entry(vet2).or_default().push(vet1);
}
/* Remove an edge */
#[allow(unused)]
pub fn remove_edge(&mut self, vet1: Vertex, vet2: Vertex) {
if vet1 == vet2 {
panic!("value error");
}
// Remove the edge vet1 - vet2
self.adj_list
.entry(vet1)
.and_modify(|v| v.retain(|&e| e != vet2));
self.adj_list
.entry(vet2)
.and_modify(|v| v.retain(|&e| e != vet1));
}
/* Add a vertex */
pub fn add_vertex(&mut self, vet: Vertex) {
if self.adj_list.contains_key(&vet) {
return;
}
// Add a new linked list to the adjacency list
self.adj_list.insert(vet, vec![]);
}
/* Remove a vertex */
#[allow(unused)]
pub fn remove_vertex(&mut self, vet: Vertex) {
// Remove the linked list for vertex vet from the adjacency list
self.adj_list.remove(&vet);
// Traverse the other vertices' lists and remove every edge incident to vet
for list in self.adj_list.values_mut() {
list.retain(|&v| v != vet);
}
}
/* Print the adjacency list */
pub fn print(&self) {
println!("Adjacency list =");
for (vertex, list) in &self.adj_list {
let list = list.iter().map(|vertex| vertex.val).collect::<Vec<i32>>();
println!("{}: {:?},", vertex.val, list);
}
}
}
/* Node structure */
typedef struct AdjListNode {
Vertex *vertex; // Vertex
struct AdjListNode *next; // Next node
} AdjListNode;
/* Find the node for a vertex */
AdjListNode *findNode(GraphAdjList *graph, Vertex *vet) {
for (int i = 0; i < graph->size; i++) {
if (graph->heads[i]->vertex == vet) {
return graph->heads[i];
}
}
return NULL;
}
/* Helper for adding an edge */
void addEdgeHelper(AdjListNode *head, Vertex *vet) {
AdjListNode *node = (AdjListNode *)malloc(sizeof(AdjListNode));
node->vertex = vet;
// Insert at the head
node->next = head->next;
head->next = node;
}
/* Helper for removing an edge */
void removeEdgeHelper(AdjListNode *head, Vertex *vet) {
AdjListNode *pre = head;
AdjListNode *cur = head->next;
// Search the linked list for the node corresponding to vet
while (cur != NULL && cur->vertex != vet) {
pre = cur;
cur = cur->next;
}
if (cur == NULL)
return;
// Remove the node corresponding to vet from the linked list
pre->next = cur->next;
// Free the memory
free(cur);
}
/* Undirected graph represented by an adjacency list */
typedef struct {
AdjListNode *heads[MAX_SIZE]; // Array of nodes
int size; // Number of nodes
} GraphAdjList;
/* Constructor */
GraphAdjList *newGraphAdjList() {
GraphAdjList *graph = (GraphAdjList *)malloc(sizeof(GraphAdjList));
if (!graph) {
return NULL;
}
graph->size = 0;
for (int i = 0; i < MAX_SIZE; i++) {
graph->heads[i] = NULL;
}
return graph;
}
/* Destructor */
void delGraphAdjList(GraphAdjList *graph) {
for (int i = 0; i < graph->size; i++) {
AdjListNode *cur = graph->heads[i];
while (cur != NULL) {
AdjListNode *next = cur->next;
if (cur != graph->heads[i]) {
free(cur);
}
cur = next;
}
free(graph->heads[i]->vertex);
free(graph->heads[i]);
}
free(graph);
}
/* Find the node for a vertex */
AdjListNode *findNode(GraphAdjList *graph, Vertex *vet) {
for (int i = 0; i < graph->size; i++) {
if (graph->heads[i]->vertex == vet) {
return graph->heads[i];
}
}
return NULL;
}
/* Add an edge */
void addEdge(GraphAdjList *graph, Vertex *vet1, Vertex *vet2) {
AdjListNode *head1 = findNode(graph, vet1);
AdjListNode *head2 = findNode(graph, vet2);
assert(head1 != NULL && head2 != NULL && head1 != head2);
// Add the edge vet1 - vet2
addEdgeHelper(head1, vet2);
addEdgeHelper(head2, vet1);
}
/* Remove an edge */
void removeEdge(GraphAdjList *graph, Vertex *vet1, Vertex *vet2) {
AdjListNode *head1 = findNode(graph, vet1);
AdjListNode *head2 = findNode(graph, vet2);
assert(head1 != NULL && head2 != NULL);
// Remove the edge vet1 - vet2
removeEdgeHelper(head1, head2->vertex);
removeEdgeHelper(head2, head1->vertex);
}
/* Add a vertex */
void addVertex(GraphAdjList *graph, Vertex *vet) {
assert(graph != NULL);
if (findNode(graph, vet) != NULL)
return;
assert(graph->size < MAX_SIZE);
AdjListNode *head = (AdjListNode *)malloc(sizeof(AdjListNode));
head->vertex = vet;
head->next = NULL;
// Add a new linked list to the adjacency list
graph->heads[graph->size++] = head;
}
/* Remove a vertex */
void removeVertex(GraphAdjList *graph, Vertex *vet) {
AdjListNode *node = findNode(graph, vet);
assert(node != NULL);
// Shift the following vertices forward to fill the gap
int i;
for (i = 0; i < graph->size; i++) {
if (graph->heads[i] == node)
break;
}
for (int j = i; j < graph->size - 1; j++) {
graph->heads[j] = graph->heads[j + 1];
}
graph->size--;
// Traverse the other vertices' lists and remove every edge incident to vet
for (int i = 0; i < graph->size; i++) {
AdjListNode *cur = graph->heads[i];
while (cur->next != NULL) {
AdjListNode *next = cur->next;
if (next->vertex == vet) {
cur->next = next->next;
free(next);
} else {
cur = next;
}
}
}
// Remove the linked list for vertex vet from the adjacency list
while (node != NULL) {
AdjListNode *next = node->next;
free(node);
node = next;
}
free(vet);
}
/* Undirected graph represented by an adjacency list */
class GraphAdjList(edges: Array<Array<Vertex?>>) {
// Adjacency list: each vertex maps to its neighbors
val adjList = HashMap<Vertex, MutableList<Vertex>>()
/* Constructor */
init {
// Add all vertices and edges
for (edge in edges) {
addVertex(edge[0]!!)
addVertex(edge[1]!!)
addEdge(edge[0]!!, edge[1]!!)
}
}
/* Get the vertex count */
fun size(): Int {
return adjList.size
}
/* Add an edge */
fun addEdge(vet1: Vertex, vet2: Vertex) {
if (!adjList.containsKey(vet1) || !adjList.containsKey(vet2) || vet1 == vet2)
throw IllegalArgumentException()
// Add the edge vet1 - vet2
adjList[vet1]?.add(vet2)
adjList[vet2]?.add(vet1)
}
/* Remove an edge */
fun removeEdge(vet1: Vertex, vet2: Vertex) {
if (!adjList.containsKey(vet1) || !adjList.containsKey(vet2) || vet1 == vet2)
throw IllegalArgumentException()
// Remove the edge vet1 - vet2
adjList[vet1]?.remove(vet2)
adjList[vet2]?.remove(vet1)
}
/* Add a vertex */
fun addVertex(vet: Vertex) {
if (adjList.containsKey(vet))
return
// Add a new linked list to the adjacency list
adjList[vet] = mutableListOf()
}
/* Remove a vertex */
fun removeVertex(vet: Vertex) {
if (!adjList.containsKey(vet))
throw IllegalArgumentException()
// Remove the linked list for vertex vet from the adjacency list
adjList.remove(vet)
// Traverse the other vertices' lists and remove every edge incident to vet
for (list in adjList.values) {
list.remove(vet)
}
}
/* Print the adjacency list */
fun print() {
println("Adjacency list =")
for (pair in adjList.entries) {
val tmp = mutableListOf<Int>()
for (vertex in pair.value) {
tmp.add(vertex._val)
}
println("${pair.key._val}: $tmp,")
}
}
}
### Undirected graph represented by an adjacency list ###
class GraphAdjList
attr_reader :adj_list
### Constructor ###
def initialize(edges)
# Adjacency list: each vertex maps to its neighbors
@adj_list = {}
# Add all vertices and edges
for edge in edges
add_vertex(edge[0])
add_vertex(edge[1])
add_edge(edge[0], edge[1])
end
end
### Get the vertex count ###
def size
@adj_list.length
end
### Add an edge ###
def add_edge(vet1, vet2)
raise ArgumentError if !@adj_list.include?(vet1) || !@adj_list.include?(vet2) || vet1 == vet2
@adj_list[vet1] << vet2
@adj_list[vet2] << vet1
end
### Remove an edge ###
def remove_edge(vet1, vet2)
raise ArgumentError if !@adj_list.include?(vet1) || !@adj_list.include?(vet2) || vet1 == vet2
# Remove the edge vet1 - vet2
@adj_list[vet1].delete(vet2)
@adj_list[vet2].delete(vet1)
end
### Add a vertex ###
def add_vertex(vet)
return if @adj_list.include?(vet)
# Add a new linked list to the adjacency list
@adj_list[vet] = []
end
### Remove a vertex ###
def remove_vertex(vet)
raise ArgumentError unless @adj_list.include?(vet)
# Remove the linked list for vertex vet from the adjacency list
@adj_list.delete(vet)
# Traverse the other vertices' lists and remove every edge incident to vet
for vertex in @adj_list
@adj_list[vertex.first].delete(vet) if @adj_list[vertex.first].include?(vet)
end
end
### Print the adjacency list ###
def __print__
puts 'Adjacency list ='
for vertex in @adj_list
tmp = @adj_list[vertex.first].map { |v| v.val }
puts "#{vertex.first.val}: #{tmp},"
end
end
end
Visualize execution
9.2.3 Efficiency comparison¶
Consider a graph with \(n\) vertices and \(m\) edges. Table 9-2 compares the time and space costs of an adjacency matrix and an adjacency list. “Adjacency list (linked lists)” corresponds to the implementation described here. “Adjacency list (hash tables)” means that every linked list has been replaced with a hash table.
Table 9-2 Comparing adjacency matrices and adjacency lists
| Adjacency matrix | Adjacency list (linked lists) | Adjacency list (hash tables) | |
|---|---|---|---|
| Check adjacency | \(O(1)\) | \(O(n)\) | \(O(1)\) |
| Add an edge | \(O(1)\) | \(O(1)\) | \(O(1)\) |
| Remove an edge | \(O(1)\) | \(O(n)\) | \(O(1)\) |
| Add a vertex | \(O(n)\) | \(O(1)\) | \(O(1)\) |
| Remove a vertex | \(O(n^2)\) | \(O(n + m)\) | \(O(n)\) |
| Memory usage | \(O(n^2)\) | \(O(n + m)\) | \(O(n + m)\) |
The adjacency list with hash tables appears to offer the best time and space efficiency in the table. In practice, however, edge operations are faster in an adjacency matrix because each takes just one array access or assignment. Overall, an adjacency matrix trades space for time, while an adjacency list trades time for space.