## Chapter 14Graph Traversal

### 14.1 Depth-First Traversal

```algorithm  dft(x)
visit(x)
FOR each y such that (x,y) is an edge DO
IF y was not visited yet THEN
dft(y)
```
A recursive algorithm implicitly recording a “backtracking” path from the root to the node currently under consideration

Visit the nodes at level i before the nodes of level i+1.

```visit(start node)
queue <- start node
WHILE queue is nor empty DO
x <- queue
FOR each y such that (x,y) is an edge
and y has not been visited yet DO
visit(y)
queue <- y
END
END
```

### 14.3 Representations of Graphs

Graphs G = (V, E) can be represented by adjacency matrices G[v1..v|V |, v1..v|V |], where the rows and columns are indexed by the nodes, and the entries G[vi, vj] represent the edges. In the case of unlabeled graphs, the entries are just boolean values.

A B C D 0 1 1 1 1 0 0 1 1 0 0 1 1 1 1 0

In case of labeled graphs, the labels themselves may be introduced into the entries.

A B C 10 4 1 15 9

Adjacency matrices require O(|V |2) space, and so they are space-efficient only when they are dense (that is, when the graphs have many edges). Time-wise, the adjacency matrices allow easy addition and deletion of edges.