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:
Add n to the end of the queue.
Set distTo[n] = distTo[v] + 1.
To Implement our graph algorithms like BreadthFirstPaths and DepthFirstPaths:
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)
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.
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.
Create a Paths API, which takes a Graph object and query the graph-processing for information.
Depth First Search
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
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.