...

/

Solution: Depth-First Graph Traversal

Solution: Depth-First Graph Traversal

Learn how to implement the depth-first traversal of a graph.

We'll cover the following...

Solution

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, ...