0% found this document useful (0 votes)
16 views2 pages

Message

Uploaded by

Krum Bozhkov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

Message

Uploaded by

Krum Bozhkov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

using System;

using System.Collections.Generic;
using System.Linq;

namespace TraverseGraph
{
class Program
{
static void Main(string[] args)
{
int verticesCount = int.Parse(Console.ReadLine());
int edgesCount = int.Parse(Console.ReadLine());

Graph graph = new Graph(verticesCount);


graph.ReadGraph(edgesCount);

int startVertex = int.Parse(Console.ReadLine());

Console.Write("Following is Depth First Traversal" + $"(starting from


vertex {startVertex})\n");

graph.DFS(startVertex);
}
}
public class Graph
{
private static int verticesCount;
private static LinkedList<int>[] adjacents;
public Graph(int _verticesCount)
{
adjacents = new LinkedList<int>[_verticesCount];

for (int i = 0; i < adjacents.Length; i++)


{
adjacents[i] = new LinkedList<int>();
}
verticesCount = _verticesCount;
}

public void AddEdge(int firstVertex, int secondVertex)


{
adjacents[firstVertex].AddLast(secondVertex);
}

public void BFS(int vertex)


{
bool[] visitedVertices = new bool[verticesCount];

LinkedList<int> queue = new LinkedList<int>();

visitedVertices[vertex] = true;
queue.AddLast(vertex);

while(queue.Any())
{
vertex = queue.First();
Console.Write(vertex + " ");
queue.RemoveFirst();
LinkedList<int> list = adjacents[vertex];
foreach(var adjacent in list)
{
if(!visitedVertices[adjacent])
{
visitedVertices[adjacent] = true;
queue.AddLast(adjacent);
}
}
}
}

public void DFS(int vertex)


{
bool[] visited = new bool[verticesCount];

DFSUtil(vertex, visited);
}

public void DFSUtil(int vertex, bool[] visited)


{
visited[vertex] = true;
Console.Write(vertex + " ");

var verticesList = adjacents[vertex];

foreach(var v in verticesList)
{
if(!visited[v])
{
DFSUtil(v, visited);
}
}
}
public void ReadGraph(int edgesCount)
{
Graph graph = new Graph(verticesCount);

for (int i = 0; i < edgesCount; i++)


{
int[] line =
Console.ReadLine().Split().Select(int.Parse).ToArray();
graph.AddEdge(line[0], line[1]);
}
}

}
}

You might also like