gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
使用C#语言给出一个使用广度优先搜索算法的示例
- User
使用C#语言给出一个使用广度优先搜索算法的示例
- Assistant
下面是一个使用广度优先搜索算法在一个图中寻找最短路径的示例程序:
using System; using System.Collections.Generic; class BFSExample { // 用于表示图的邻接表 private Dictionary<int, List<int>> graph; public BFSExample() { // 初始化图的邻接表 graph = new Dictionary<int, List<int>>(); graph.Add(1, new List<int>() { 2, 3 }); graph.Add(2, new List<int>() { 1, 4, 5 }); graph.Add(3, new List<int>() { 1 }); graph.Add(4, new List<int>() { 2 }); graph.Add(5, new List<int>() { 2 }); } public void BFS(int start, int target) { // 记录已访问的节点 HashSet<int> visited = new HashSet<int>(); // 用于存储节点的队列 Queue<int> queue = new Queue<int>(); // 用于存储节点的前驱节点 Dictionary<int, int> prev = new Dictionary<int, int>(); // 初始化起始节点 queue.Enqueue(start); visited.Add(start); prev.Add(start, -1); while (queue.Count > 0) { int currentNode = queue.Dequeue(); // 到达目标节点,打印路径并退出循环 if (currentNode == target) { PrintPath(prev, target); break; } // 遍历邻居节点 List<int> neighbors = graph[currentNode]; foreach (int neighbor in neighbors) { if (!visited.Contains(neighbor)) { queue.Enqueue(neighbor); visited.Add(neighbor); prev.Add(neighbor, currentNode); } } } } private void PrintPath(Dictionary<int, int> prev, int target) { List<int> path = new List<int>(); int currentNode = target; // 从目标节点逆序回溯到起始节点,得到最短路径 while (currentNode != -1) { path.Add(currentNode); currentNode = prev[currentNode]; } // 反转路径,得到正序的最短路径 path.Reverse(); // 输出最短路径 Console.WriteLine("最短路径: " + string.Join(" → ", path)); } static void Main(string[] args) { BFSExample bfsExample = new BFSExample(); bfsExample.BFS(1, 4); } }