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