DFS and BFS visit all nodes explorable from a given start node. To explore an entire graph that is not necessarily connected, we can do something like this:
while there are still unvisited nodes:
u = an unvisited node
DFS(u)
In this way, all nodes in the graph get visited. In Problems 1 and 2, assume that we are using an approach like this to visit all nodes in the graph in question.
What’s the runtime of DFS on a graph with \(v\) nodes and \(e\) edges?
What’s the runtime of BFS on a graph with \(v\) nodes and \(e\) edges?
Try running BFS(2) on the following undirected graph:
Write the order in which nodes are visited, then label each node with the path length to the origin (2). What do you notice about the visit order of BFS?
Consider this: a tree is a special kind of undirected graph with only one path between all pairs of nodes (you could also define it to be a directed graph with edges pointing from parent to child).
DFS(root) on a binary search tree corresponds to which tree traversal?
BFS(root) on any tree corresponds to which tree traversal?
For this problem, let’s stick to thinking about undirected graphs. A connected component is a subgraph that is connected. The number of connected components in a graph is the smallest number of components that, taken together, comprise the whole graph. For example, the following graph has 3 connected components:
Suppose you have an adjacency list representation of a graph. Devise an algorithm to count the number of connected components. Hint: What can you say about the subgraph containing the set of nodes visited by a DFS and all edges that connect pairs of those nodes (this is called the induced subgraph)?