depth first search in csharp

Here's the implementation of depth-first search algorithm in C#:

main.cs
using System;
using System.Collections.Generic;

public class Graph
{
    private int V; // Number of vertices

    // Adjacency list representation of the graph
    private List<int>[] adj;

    // Constructor
    public Graph(int v)
    {
        V = v;
        adj = new List<int>[V];
        for (int i = 0; i < V; i++)
        {
            adj[i] = new List<int>();
        }
    }

    // Method to add an edge between two vertices
    public void AddEdge(int v, int w)
    {
        adj[v].Add(w);
    }

    // Depth-first search traversal using recursion
    private void DFS(int v, bool[] visited)
    {
        visited[v] = true;
        Console.Write(v + " ");

        foreach (var i in adj[v])
        {
            if (!visited[i])
            {
                DFS(i, visited);
            }
        }
    }

    // Method to traverse the graph using Depth-first search
    public void TraverseDFS(int startVertex)
    {
        bool[] visited = new bool[V];
        DFS(startVertex, visited);
    }
}

public class Program
{
    static void Main()
    {
        int v = 4;
        Graph graph = new Graph(v);
 
        graph.AddEdge(0, 1);
        graph.AddEdge(0, 2);
        graph.AddEdge(1, 2);
        graph.AddEdge(2, 0);
        graph.AddEdge(2, 3);
        graph.AddEdge(3, 3);

        Console.WriteLine("Following is Depth First Traversal (starting from vertex 2)");
 
        graph.TraverseDFS(2);
    }
}
1434 chars
70 lines

In this implementation, we first define a Graph class that contains the adjacency list representation of the graph and two methods: AddEdge to add an edge between two vertices and TraverseDFS to traverse the graph using Depth-first search.

The DFS method is a recursive method that starts at a given vertex v and explores as far as possible along each branch before backtracking. It marks each visited vertex using a Boolean array visited.

Finally, in the Main method, we create a graph and add some edges to it, and then call the TraverseDFS method to start the depth-first search traversal from a specified vertex.

gistlibby LogSnag