有向图的寻径算法(bfs带路径记录)

既然都用到dfs了,那就再总结一下bfs。
bfs只要就是一个记录遍历元素的问题,一般是使用队列
还是dfs一样的,用领接表记录有向图

	private static List<String> getlRoadByBFS(String start, String end, List<Line> datas) {	
		Map<String, List<String>> ljb = new HashMap<String, List<String>>(6);
		for (Line line : datas) {
			if (ljb.containsKey(line.start)) {
				ljb.get(line.start).add(line.end);
			} else {
				List<String> li = new ArrayList<String>();
				li.add(line.end);
				ljb.put(line.start, li);
			}
		}		
		return getRoadByBFS(start,end,ljb);		
	}	
	
	private static List<String>getRoadByBFS(String start,String end,Map<String, List<String>> ljb){
		Queue <String>backup = new LinkedList<>();//遍历记录
		Set<String> has = new HashSet<>();//记录已经到达节点
		Map<String,String> memory =new HashMap<>();//记录每点对应的上一步节点
		backup.add(start);
		has.add(start);
		while(!backup.isEmpty()) {
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,针对你的问题,我可以给出以下的 Python 代码实现: ``` from collections import deque # 定义有向的邻接表表示 graph = { 'A': {'B': 1, 'C': 4}, 'B': {'D': 2}, 'C': {'D': 1}, 'D': {'E': 3}, 'E': {} } # 定义广度优先算法求最短路径 def bfs_shortest_path(graph, start, end): queue = deque([(start, [start])]) # 使用双向队列,初始化为起点 visited = set() # 记录已访问的节点 while queue: node, path = queue.popleft() # 取出队列中的节点和路径 if node not in visited: # 如果节点没有被访问过 visited.add(node) # 标记为已访问 if node == end: # 如果找到了终点 return path # 返回路径 for neighbor, weight in graph[node].items(): # 遍历邻居节点 if neighbor not in visited: # 如果邻居节点没有被访问过 queue.append((neighbor, path + [neighbor])) # 将邻居节点加入队列,并记录路径 return None # 如果没有找到路径,返回 None # 测试代码 start = 'A' end = 'E' shortest_path = bfs_shortest_path(graph, start, end) if shortest_path: print(f"The shortest path from {start} to {end} is: {' -> '.join(shortest_path)}") else: print(f"There is no path from {start} to {end}") ``` 在这个例子中,我们定义了一个有向的邻接表表示,使用 `deque` 实现双向队列,并采用广度优先搜索算法来搜索最短路径。最后,我们利用测试代码对算法进行测试,输出最短路径结果。 希望这个例子能够帮助你理解如何利用广度优先算法找出最短路径

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值