-
Notifications
You must be signed in to change notification settings - Fork 1
/
BreadthFirstSearch.cs
44 lines (38 loc) · 1.28 KB
/
BreadthFirstSearch.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
using AlgorithmsAndDataStructures.DataStructures.Graph;
using System.Collections.Generic;
using System.Linq;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.Search
{
public class BreadthFirstSearch
{
#pragma warning disable CA1822 // Mark members as static
public List<int> Traverse(GraphVertex<int>[] graph)
#pragma warning restore CA1822 // Mark members as static
{
if (graph is null)
{
return new List<int>(0);
}
var result = new List<int>();
var traversalQueue = new Queue<int>();
var visited = new HashSet<int>();
traversalQueue.Enqueue(0);
while (traversalQueue.Any())
{
var current = traversalQueue.Dequeue();
result.Add(graph[current].Value);
visited.Add(current);
var adjacentNodes = graph[current].AdjacentVertices;
for (var i = 0; i < adjacentNodes.Count; i++)
{
if (visited.Contains(adjacentNodes[i]))
{
continue;
}
traversalQueue.Enqueue(adjacentNodes[i]);
}
}
return result;
}
}
}