From 9a6a7ef5fd562cff7dc45ba1bca25bc4052afc4f Mon Sep 17 00:00:00 2001 From: Tavi Truman Date: Fri, 17 Mar 2023 16:59:37 -0700 Subject: [PATCH] Create BFS_DFS_PropertyGraph.cs 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 called visited. They print out the visited vertices in the order they are visited during the traversal. --- BFS_DFS_PropertyGraph.cs | 84 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 BFS_DFS_PropertyGraph.cs diff --git a/BFS_DFS_PropertyGraph.cs b/BFS_DFS_PropertyGraph.cs new file mode 100644 index 0000000..47183bd --- /dev/null +++ b/BFS_DFS_PropertyGraph.cs @@ -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 Vertices { get; set; } + public Dictionary 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(); + var queue = new Queue(); + + 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(); + DFSUtil(startVertexId, visited); + } + + private void DFSUtil(int vertexId, HashSet 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. + } +}