Graph Traversals and Implementations
BFS (Breadth First Search)
This algorithm of exploring a vertex's immediate children before moving on to its grandchildren is known as Breadth First Traversal.
Initialize the a queue with the starting vertex and mark that vertex.
Repeat until the queue is empty:
Remove vertex v from the front of the queue.
For each unmarked neighbor n of v:
Mark n.
Add n to the end of the queue.
Set edgeTo[n] = v.
Set distTo[n] = distTo[v] + 1.
Graph API
To Implement our graph algorithms like BreadthFirstPaths and DepthFirstPaths:
An API for Graphs.
An underlying data structure to represent the graphs.
The API uses integers to represent vertices. Map<Label, Integer>
is required to lookup vertices by labels.
Number of vertices must be specified in advance.
Does not support weights on nodes or edges.
Has no method for getting the degree for a vertex.
degree(Graph G, int v)
print(Graph G)
Graph Representations
The choice of data structure to represent the graph should have implications on both runtime and memory usage.
Adjacency Matrix
Use a 2D array. There is an edge connecting vertex s
to t
if that corresponding cell is 1, which represents true
.
Edge Sets
Use a single set to create a collection of all edges.
Adjacency Lists
Use an array of lists, indexed by vertex number. Each index contains the index of its adjancent vertices.
Implementation
Runtime
Representation
addEdge(s, t)
for(w : adj(v))
print()
hasEdge(s, t)
space used
Adjacency Matrix
Θ(1)
Θ(V)
Θ(V^2)
Θ(1)
Θ(V^2)
Edge Sets
Θ(1)
Θ(E)
Θ(E)
Θ(E)
Θ(E)
Adjacency Lists
Θ(1)
Θ(1) to Θ(V)
Θ(V+E)
Θ(degree(v))
Θ(V+E)
Implementation
Create a Paths API, which takes a Graph object and query the graph-processing for information.
Depth First Search
Runtime
The DepthFirstPaths constructor:
O(V+E)
.Each vertex is visited at most once (
O(V)
).
Each edge is considered at most twice (
O(E)
).
Breadth First Search
Graph Problems
Adjacency List Based Graphs
Problem|Description|Solution|Efficiency (adj. list) |---|---|---|---| s-t paths|Find a path from s to every reachable vertex.|DepthFirstPaths|O(V+E)
time, Θ(V)
space. s-t shortest paths|Find a shortest path from s to every reachable vertex.|BreadthFirstPaths|O(V+E)
time, Θ(V)
space.
Adjacency Matrix Based Graphs
Problem|Description|Solution|Efficiency (adj. list) |---|---|---|---| s-t paths|Find a path from s to every reachable vertex.|DepthFirstPaths|O(V^2)
time, Θ(V)
space. s-t shortest paths|Find a shortest path from s to every reachable vertex.|BreadthFirstPaths|O(V^2)
time, Θ(V)
space.
Last updated