[Глава 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
28
Chapter5_BreadthFirstSearch/Program.cs
Normal file
28
Chapter5_BreadthFirstSearch/Program.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using GrokAlgorithms.Chapter5_BreadthFirstSearch;
|
||||
|
||||
int count = 0;
|
||||
|
||||
// Команда для построения дерева
|
||||
TreeNode<int> BuildTreeCommand(int value, int depth, int branchingFactor)
|
||||
{
|
||||
var node = new TreeNode<int>(value) { Comment = $"{count++}" };
|
||||
if (depth == 0) return node;
|
||||
|
||||
for (int i = 1; i <= branchingFactor; i++)
|
||||
node.Children.Add(BuildTreeCommand(value + i * 10, depth - 1, branchingFactor));
|
||||
return node;
|
||||
}
|
||||
|
||||
// Команда для печати дерева
|
||||
void PrintTreeCommand(TreeNode<int> node, string indent = "")
|
||||
{
|
||||
Console.WriteLine($"{indent}{node.Value} [{node.Comment}] {(node.Selected ? " Selected" : "")}");
|
||||
foreach (var child in node.Children)
|
||||
PrintTreeCommand(child, indent + " ");
|
||||
}
|
||||
|
||||
var root = BuildTreeCommand(1, 3, 2);
|
||||
var found = Bfs.Search(root, (num) => num > 25);
|
||||
if (found != null)
|
||||
found.Selected = true;
|
||||
PrintTreeCommand(root);
|
||||
18
Chapter5_BreadthFirstSearch/TreeNode.cs
Normal file
18
Chapter5_BreadthFirstSearch/TreeNode.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace GrokAlgorithms.Chapter5_BreadthFirstSearch;
|
||||
|
||||
|
||||
public class TreeNode<T>
|
||||
{
|
||||
public T Value { get; init; }
|
||||
public string Comment { get; init; }
|
||||
public List<TreeNode<T>> Children { get; init; }
|
||||
public bool Selected { get; set; }
|
||||
|
||||
public TreeNode(T value)
|
||||
{
|
||||
Value = value;
|
||||
Comment = "";
|
||||
Children = new List<TreeNode<T>>();
|
||||
Selected = false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user