-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBreadthFirstSearch.cs
More file actions
37 lines (30 loc) · 1.07 KB
/
BreadthFirstSearch.cs
File metadata and controls
37 lines (30 loc) · 1.07 KB
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
using System.Collections.Generic;
using System.Linq;
using AlgorithmsAndDataStructures.DataStructures.Graph;
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;
}
}