[Глава 5] Поиск в ширину
This commit is contained in:
23
Chapter5_BreadthFirstSearch/Bfs.cs
Normal file
23
Chapter5_BreadthFirstSearch/Bfs.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
using GrokAlgorithms.Chapter5_BreadthFirstSearch;
|
||||
|
||||
static class Bfs
|
||||
{
|
||||
public static TreeNode<T>? Search<T>(TreeNode<T> root, Func<T, bool> condition)
|
||||
{
|
||||
Queue<TreeNode<T>> queue = new();
|
||||
queue.Enqueue(root);
|
||||
HashSet<TreeNode<T>> visited = [];
|
||||
while (queue.Count > 0)
|
||||
{
|
||||
var curr = queue.Dequeue();
|
||||
if (visited.Contains(curr))
|
||||
continue;
|
||||
if (condition(curr.Value))
|
||||
return curr;
|
||||
foreach (var child in curr.Children)
|
||||
queue.Enqueue(child);
|
||||
visited.Add(curr);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user