codementor on Nostr: Learn: Breadth-first search (BFS) BFS visits the start node, then all its neighbors, ...
Learn: Breadth-first search (BFS)
BFS visits the start node, then all its neighbors, then their neighbors, and so on: rings of growing distance.
It needs a Queue<T> for the nodes to visit and a HashSet<T> for the nodes already seen.
```csharp
var graph = new Dictionary<int, int[]> { [1] = [2, 3], [2] = [4], [3] = [4, 5], [4] = [], [5] = [] };
var seen = new HashSet<int> { 1 };
var queue = new Queue<int>([1]);
var order = new List<int>();
while (queue.TryDequeue(out int n))
{
order.Add(n);
foreach (int next in graph[n]) if (seen.Add(next)) queue.Enqueue(next); // mark when queued
}
Console.WriteLine(string.Join(" ", order));
```
It prints 1 2 3 4 5. Node 4 is reached twice, but queued once.
Cost: O(V + E). Because it goes ring by ring, BFS finds the route with the fewest edges.
#tg001 · TG-001-N
Published at
2026-10-27 17:08:04 UTCEvent JSON
{
"id": "d296f6a557eed09ed56ff939b10820dada3fed5ac60a4adcb6cbc1eb7b45ad9b",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1793120884,
"kind": 1,
"tags": [
[
"t",
"tg001"
]
],
"content": "Learn: Breadth-first search (BFS)\n\nBFS visits the start node, then all its neighbors, then their neighbors, and so on: rings of growing distance.\n\nIt needs a Queue\u003cT\u003e for the nodes to visit and a HashSet\u003cT\u003e for the nodes already seen.\n\n```csharp\nvar graph = new Dictionary\u003cint, int[]\u003e { [1] = [2, 3], [2] = [4], [3] = [4, 5], [4] = [], [5] = [] };\nvar seen = new HashSet\u003cint\u003e { 1 };\nvar queue = new Queue\u003cint\u003e([1]);\nvar order = new List\u003cint\u003e();\nwhile (queue.TryDequeue(out int n))\n{\n order.Add(n);\n foreach (int next in graph[n]) if (seen.Add(next)) queue.Enqueue(next); // mark when queued\n}\nConsole.WriteLine(string.Join(\" \", order));\n```\n\nIt prints 1 2 3 4 5. Node 4 is reached twice, but queued once.\n\nCost: O(V + E). Because it goes ring by ring, BFS finds the route with the fewest edges.\n\n#tg001 · TG-001-N",
"sig": "4781916f253d7f2eebf2b73ff28e13ab9d30b6b674aa481f3c6edc33e60b756eb718b9eab3b6b67af374243800dfec7dd5a8f1f9580cd5ea51ab6442631a2586"
}