用优先队列的分支限界法求解最短路径

思路

辅助数据结构:
(1)优先队列
(2)path[i] 数组,记录到索引为 i 的节点的已知最短路径的前一个节点
(3)distTo[i] 数组,记录到索引为 i 的节点的已知最短距离
使用深度优先搜索
1、首先将起点加入优先队列,随后将其所有子节点加入优先队列,更新三个辅助数据结构。
2、从优先队列中选路径最短的边的节点,依次访问其子节点,若根节点到该节点(假设该节点索引为 i )的距离小于 disTo[i] 的节点,则将其加入优先队列并更新更改 path[i] 以及 distTo[i] ,否则将其删除该节点以及它的所有子节点。
3、重复 2 操作直到队列为空。

疑惑点:
如果删掉一个节点后,没有该节点以及它的所有子节点,会漏掉最优解吗?
答:不会,因为每次选取的时候都选取路径最短的边的节点,如果要删除一个节点 n ,说明根节点到节点 n 的距离有更短的路径存在,所以要删除的节点 n 不会影响到其他节点。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于分支限界求解源点0到终点6的最路径及其路径长度的Java实现: ```java import java.util.*; public class ShortestPath { static int[][] graph = {{0, 2, 1, 4, 5, 1, 6}, {2, 0, 4, 1, 3, 2, 0}, {1, 4, 0, 1, 2, 3, 0}, {4, 1, 1, 0, 0, 1, 0}, {5, 3, 2, 0, 0, 2, 0}, {1, 2, 3, 1, 2, 0, 0}, {6, 0, 0, 0, 0, 0, 0}}; static int start = 0; // 源点 static int end = 6; // 终点 static class Node implements Comparable<Node> { int index; // 当前节点的编号 int distance; // 从源点到当前节点的距离 Node(int index, int distance) { this.index = index; this.distance = distance; } @Override public int compareTo(Node o) { return Integer.compare(this.distance, o.distance); } } public static void main(String[] args) { int[] path = shortestPath(); System.out.println("最路径为:" + Arrays.toString(path)); System.out.println("路径长度为:" + path[end]); } private static int[] shortestPath() { PriorityQueue<Node> queue = new PriorityQueue<>(); queue.offer(new Node(start, 0)); int[] distances = new int[graph.length]; Arrays.fill(distances, Integer.MAX_VALUE); distances[start] = 0; int[] preNodes = new int[graph.length]; Arrays.fill(preNodes, -1); while (!queue.isEmpty()) { Node curr = queue.poll(); int currIndex = curr.index; int currDistance = curr.distance; if (currIndex == end) { // 已经找到最路径,退出循环 break; } for (int i = 0; i < graph[currIndex].length; i++) { if (graph[currIndex][i] != 0 && currDistance + graph[currIndex][i] < distances[i]) { distances[i] = currDistance + graph[currIndex][i]; preNodes[i] = currIndex; queue.offer(new Node(i, distances[i])); } } } // 从终点往前推,获取最路径 int[] path = new int[graph.length]; int index = end; int count = 0; while (index != -1) { path[count++] = index; index = preNodes[index]; } for (int i = 0; i < count / 2; i++) { int temp = path[i]; path[i] = path[count - i - 1]; path[count - i - 1] = temp; } return path; } } ``` 在上述代码中,我们采用了优先队列来存储待扩展节点,并按照节点到源点的距离从小到大排序,每次取出距离最小的节点进行扩展。distances数组用于记录源点到各个节点的最路径长度,preNodes数组用于记录每个节点在最路径中的前一个节点。最后,我们从终点往前推,获取最路径,并将路径上的节点编号存储在path数组中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值