-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathBreadthFirstSearch.cs
68 lines (52 loc) · 2.08 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
using System.Collections.Generic;
using PracticeQuestionsSharp.DataStructures;
namespace PracticeQuestionsSharp.Algorithms
{
public static class BreadthFirstSearch
{
//Iterative depth-first search that returns the node with the target data.
public static GraphNode<T> BFS<T>(this SimpleGraph<T> graph, T target)
{
if (graph == null || graph.Nodes.Count == 0) return null;
var visited = new HashSet<GraphNode<T>>();
var queue = new DataStructures.Queue<GraphNode<T>>();
queue.Enqueue(graph.Root);
while (!queue.IsEmpty)
{
GraphNode<T> curr = queue.Dequeue();
if (visited.Contains(curr)) continue;
if (curr.Data.Equals(target)) return curr;
visited.Add(curr);
foreach (GraphNode<T> neighbor in curr.Neighbors) queue.Enqueue(neighbor);
}
return null;
}
//Iterative depth-first search that returns the path to the target
public static List<GraphNode<T>> BFSPathTo<T>(this SimpleGraph<T> graph, T target)
{
if (graph == null || graph.Nodes.Count == 0) return null;
var visited = new HashSet<GraphNode<T>>();
var queue = new DataStructures.Queue<GraphNode<T>>();
queue.Enqueue(graph.Root);
GraphNode<T> curr = null;
var path = new List<GraphNode<T>>();
while (!queue.IsEmpty)
{
curr = queue.Dequeue();
if (visited.Contains(curr)) continue;
if (curr.Data.Equals(target)) break;
visited.Add(curr);
foreach (GraphNode<T> neighbor in curr.Neighbors) queue.Enqueue(neighbor);
}
if (!curr.Data.Equals(target)) return null;
while (curr.Origin != null && !curr.Equals(graph.Root))
{
path.Add(curr);
curr = curr.Origin;
}
path.Add(curr);
path.Reverse();
return path;
}
}
}