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 visitedint V = myGraph.graph.Length;bool[] visited = new bool[V];// Create a stack for DFSStack<int> stack = new Stack<int>();// Result stringstring result = "";// Push the sourcestack.Push(source);while (stack.Count > 0){// Pop a vertex from stacksource = 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 itwhile (temp != null){int data = temp.Vertex;if (!visited[data]){stack.Push(data);}temp = temp.Next;}}return result;}// Main to test the above programstatic 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 ...