-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS_DFS_PropertyGraph.cs
84 lines (68 loc) · 2.26 KB
/
BFS_DFS_PropertyGraph.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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.
}
}