Search⌘ K
AI Features

Solution: Depth-First Graph Traversal

Explore how to implement depth-first search for graph traversal by using a stack and backtracking to visit all nodes. Understand the time complexity of O(V + E) where V is vertices and E is edges. This lesson helps you apply DFS solutions effectively in coding interviews.

We'll cover the following...

Solution

DFS
Graph.cs
class Program
{
/// <summary>
/// Method to print a DFS of a graph.
/// </summary>
/// <param name="graph">The graph.</param>
/// <param name="source">Starting vertex.</param>
public static string DFS(Graph myGraph, int source)
{
// Initialize all the vertices as not visited
int V = myGraph.graph.Length;
bool[] visited = new bool[V];
// Create a stack for DFS
Stack<int> stack = new Stack<int>();
// Result string
string result = "";
// Push the source
stack.Push(source);
while (stack.Count > 0)
{
// Pop a vertex from stack
source = stack.Pop();
if (!visited[source])
{
result += source;
visited[source] = true;
}
AdjNode temp = myGraph.graph[source];
// Get all adjacent vertices of the popped vertex source.
// If a adjacent has not been visited, then push it
while (temp != null)
{
int data = temp.Vertex;
if (!visited[data])
{
stack.Push(data);
}
temp = temp.Next;
}
}
return result;
}
// Main to test the above program
static void Main(string[] args)
{
int V = 5;
Graph g = new Graph(V);
g.AddEdge(0, 1);
g.AddEdge(0, 2);
g.AddEdge(1, 3);
g.AddEdge(1, 4);
Console.WriteLine(DFS(g, 0));
}
}

Explanation

The depth-first graph algorithm uses the idea of backtracking. We exhaustively search all the nodes by going ahead, if possible, or else by backtracking.

Here, to backtrack means to move forward as long as there are no more nodes in the current path, then move backward on the same path to find nodes to traverse.

In the above solution, we use a stack to implement depth-first graph traversal.

Time complexity

Let EE ...