-
Notifications
You must be signed in to change notification settings - Fork 1
/
BreadthFirstSearch.cs
70 lines (60 loc) · 2.16 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
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
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.GraphTraversal
{
public static class BreadthFirstSearch
{
public static IEnumerable<T> Explore<T>(T start, Func<T, IEnumerable<T>> getNeighbours, Func<T, bool> isEnd = null)
{
return Bfs(start, getNeighbours, false, isEnd);
}
private static IEnumerable<T> Bfs<T>(T start, Func<T, IEnumerable<T>> getNeighbours, bool pathOnly,
Func<T, bool> isEnd = null)
{
var visitedFrom = new Dictionary<T, T>();
var toVisit = new Queue<T>();
toVisit.Enqueue(start);
visitedFrom.Add(start, default(T));
while (toVisit.Any())
{
var current = toVisit.Dequeue();
if (!pathOnly)
{
yield return current;
}
if (isEnd != null && isEnd(current))
{
if (pathOnly)
{
var path = new Queue<T>();
while (!current.Equals(start))
{
path.Enqueue(current);
current = visitedFrom[current];
}
path.Enqueue(current);
while (path.Any())
{
yield return path.Dequeue();
}
}
yield break;
}
var neighbours = getNeighbours(current)
.Where(n => !visitedFrom.ContainsKey(n))
.Reverse()
.ToList();
foreach (var neighbour in neighbours)
{
toVisit.Enqueue(neighbour);
visitedFrom.Add(neighbour, current);
}
}
}
public static IEnumerable<T> FindPath<T>(T start, Func<T, IEnumerable<T>> getNeighbours, Func<T, bool> isEnd = null)
{
return Bfs(start, getNeighbours, true, isEnd);
}
}
}