feat: Added a hashset of visited nodes so bfs can be used on graphs

This commit is contained in:
Austin Noska
2019-06-27 10:57:00 -04:00
parent 8c160c77c4
commit 7cc5a47d6a

View File

@@ -163,7 +163,7 @@ namespace ICD.Common.Utils
} }
/// <summary> /// <summary>
/// Returns all of the nodes in the tree via breadth-first search. /// Returns all of the nodes in the graph via breadth-first search.
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="root"></param> /// <param name="root"></param>
@@ -171,6 +171,7 @@ namespace ICD.Common.Utils
/// <returns></returns> /// <returns></returns>
private static IEnumerable<T> BreadthFirstSearchIterator<T>(T root, Func<T, IEnumerable<T>> getChildren) private static IEnumerable<T> BreadthFirstSearchIterator<T>(T root, Func<T, IEnumerable<T>> getChildren)
{ {
IcdHashSet<T> visited = new IcdHashSet<T> {root};
Queue<T> process = new Queue<T>(); Queue<T> process = new Queue<T>();
process.Enqueue(root); process.Enqueue(root);
@@ -179,10 +180,13 @@ namespace ICD.Common.Utils
{ {
yield return current; yield return current;
foreach (T child in getChildren(current)) foreach (T child in getChildren(current).Where(c => !visited.Contains(c)))
{
visited.Add(child);
process.Enqueue(child); process.Enqueue(child);
} }
} }
}
/// <summary> /// <summary>
/// Returns the shortest path from root to destination via breadth-first search. /// Returns the shortest path from root to destination via breadth-first search.