Skip to content

Commit

Permalink
Create BFS_DFS_PropertyGraph.cs
Browse files Browse the repository at this point in the history
n the following C# code, I've added Breadth-First Search (BFS) and Depth-First Search (DFS) methods to the PropertyGraph class. The BFS and DFS methods take an integer startVertexId as an argument, which represents the starting vertex ID for the traversal.
The BFS method uses a queue to traverse the graph in layers, while the DFS method uses a recursive helper function called DFSUtil to perform a depth-first traversal. Both methods mark vertices as visited using a HashSet<int> called visited. They print out the visited vertices in the order they are visited during the traversal.
  • Loading branch information
TaviTruman authored Mar 17, 2023
1 parent f870850 commit 9a6a7ef
Showing 1 changed file with 84 additions and 0 deletions.
84 changes: 84 additions & 0 deletions BFS_DFS_PropertyGraph.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;

// Vertex and Edge classes remain unchanged from the previous example.

public class PropertyGraph
{
public Dictionary<int, Vertex> Vertices { get; set; }
public Dictionary<int, Edge> Edges { get; set; }

// AddVertex and AddEdge methods remain unchanged from the previous example.

public void BFS(int startVertexId)
{
if (!Vertices.ContainsKey(startVertexId))
{
Console.WriteLine("The specified start vertex does not exist.");
return;
}

var visited = new HashSet<int>();
var queue = new Queue<Vertex>();

visited.Add(startVertexId);
queue.Enqueue(Vertices[startVertexId]);

while (queue.Count > 0)
{
Vertex current = queue.Dequeue();
Console.WriteLine($"Visited vertex: {current.Id}");

foreach (var edge in Edges.Values)
{
if (edge.Source.Id == current.Id && !visited.Contains(edge.Target.Id))
{
visited.Add(edge.Target.Id);
queue.Enqueue(edge.Target);
}
}
}
}

public void DFS(int startVertexId)
{
if (!Vertices.ContainsKey(startVertexId))
{
Console.WriteLine("The specified start vertex does not exist.");
return;
}

var visited = new HashSet<int>();
DFSUtil(startVertexId, visited);
}

private void DFSUtil(int vertexId, HashSet<int> visited)
{
visited.Add(vertexId);
Console.WriteLine($"Visited vertex: {vertexId}");

foreach (var edge in Edges.Values)
{
if (edge.Source.Id == vertexId && !visited.Contains(edge.Target.Id))
{
DFSUtil(edge.Target.Id, visited);
}
}
}
}

public class Program
{
public static void Main()
{
var graph = new PropertyGraph();

// Add vertices and edges as shown in the previous example.

Console.WriteLine("Breadth-First Search:");
graph.BFS(1); // Replace '1' with the desired starting vertex ID.

Console.WriteLine("Depth-First Search:");
graph.DFS(1); // Replace '1' with the desired starting vertex ID.
}
}

0 comments on commit 9a6a7ef

Please sign in to comment.