-
Notifications
You must be signed in to change notification settings - Fork 292
/
BreadthFirst.cs
47 lines (38 loc) · 1.17 KB
/
BreadthFirst.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
using System.Collections.Generic;
using Advanced.Algorithms.DataStructures.Graph;
namespace Advanced.Algorithms.Graph;
/// <summary>
/// Bread First Search implementation.
/// </summary>
public class BreadthFirst<T>
{
/// <summary>
/// Returns true if item exists.
/// </summary>
public bool Find(IGraph<T> graph, T vertex)
{
return Bfs(graph.ReferenceVertex, new HashSet<T>(), vertex);
}
/// <summary>
/// BFS implementation.
/// </summary>
private bool Bfs(IGraphVertex<T> referenceVertex,
HashSet<T> visited, T searchVertex)
{
var bfsQueue = new Queue<IGraphVertex<T>>();
bfsQueue.Enqueue(referenceVertex);
visited.Add(referenceVertex.Key);
while (bfsQueue.Count > 0)
{
var current = bfsQueue.Dequeue();
if (current.Key.Equals(searchVertex)) return true;
foreach (var edge in current.Edges)
{
if (visited.Contains(edge.TargetVertexKey)) continue;
visited.Add(edge.TargetVertexKey);
bfsQueue.Enqueue(edge.TargetVertex);
}
}
return false;
}
}