文章目录
有向无权图-最短路径算法
无权图的最短路径算法:某一点到任意一点的最短路径
最短路径问题不仅是基础性的,更是关键性的挑战,其核心目标在于确定从一个顶点到任意一个顶点的最短路径(path)。在无权图中,由于所有边的权重被视为一致,使得无权图的最短路径问题在算法处理上相对简化,然而,这并不意味着其缺乏实际应用的意义,实际上,它在多个领域中仍具有不可忽视的实用价值。
如下图所示,我们选用节点V3开始,找到V3到V1、V2、V3、V4、V5、V6、V7这些结点需要的最短路径是多少?
注:因为是无权图所以每条边的权重都为1,不需要考虑出边的权重大小
我们可以基于图的BFS(广度优先搜索算法)对无权图进行最短路径计算,步骤如下:
-
初始化:创建一个队列queue,将起始顶点v入队,并标记为已访问。同时,创建一个数组(shortPath)来记录,其中shortPath[x][0]代表是否已经被访问、shortPath[x][1]代表到目标定点的最短距离、shortPath[x][2]代表当前第x个顶点的邻节点,所有都初始化为0。
-
开始搜索:首先将出发首节点装入队列中,并且设置相应的shortPath标识,接下来调用shortFinding()方法进行对shortPath数组的填充。
- 情况一: 如果queue队列为空,表示所有结点都搜索到了,直接退出即可
- 情况二: 队列不为空,遍历队列中未被访问到的节点,设置访问状态、最短路径需要是入节点的shortPath[x][1] + 1,入结点编号为shortFinding()方法中参数列表中的up参数,表示谁是起点。
- 分别将queue队列中元素出队,并且将该元素的所有邻接点加入到队列中,然后递归进行下一次的搜索查找。
-
结果返回: 将shortPath数组返回
-
图解
代码
/**
* 有向图
* @author sean
* @version 1.0
* @date 2024-3-19 15:34
*/
public class DirectGraph {
/**
* 结点集合
*/
private List<String> node;
/**
* 邻接矩阵
*/
private int[][] matrix;
/**
* 构造
*/
public DirectGraph(String[] nodes) {
node = new ArrayList<>(Arrays.asList(nodes));
matrix = new int[node.size()][node.size()];
}
/**
* 生成最短路径数组
* @param x 从哪个结点出发
* @return 最短路径数组
*/
public int[][] shortFinding(int x) {
Queue<Integer> queue = new ArrayDeque<>();
for (int i = 0; i < matrix[x - 1].length; i++) {
if (matrix[x - 1][i] == 1) {
queue.add(i);
}
}
int[][] shortPath = new int[node.size()][3];
// 表示被访问过 表示到2的距离 表示目的节点编号从1开始
shortPath[x - 1][0] = 1;
shortPath[x - 1][1] = 0;
shortPath[x - 1][2] = x;
shortFinding(shortPath, queue, x);
return shortPath;
}
/**
* 从某个结点出发到所有节点的最短路径
* @param shortPathFlag 最短路径数组
* @param queue 结点队列
* @param up 起始结点
*/
public void shortFinding(int[][] shortPathFlag,Queue<Integer> queue, int up) {
if (queue.isEmpty()) {
return;
}
for (Integer sno : queue) {
if (shortPathFlag[sno][0] == 1) {
continue;
}
// 拿到 v1 v6
shortPathFlag[sno][0] = 1;
// 记录当前的最短路径
shortPathFlag[sno][1] = shortPathFlag[up - 1][1] + matrix[up - 1][sno];
shortPathFlag[sno][2] = up;
}
while (!queue.isEmpty()) {
Integer removeSno = queue.remove();
for (int i = 0; i < matrix[removeSno].length; i++) {
// 是邻接点 且 未被访问过
if (matrix[removeSno][i] == 1 && shortPathFlag[i][0] != 1) {
queue.add(i);
}
}
// 回溯处理队列中未被访问的结点 为当前结点的所有邻接点
shortFinding(shortPathFlag, queue, removeSno + 1);
}
}
}
## 这里shortPath数组只有三列,
## 分别表示 visit dirt path
## 并没有stat,数组下标就代表了当前结点的编号
[1, 1, 3]
[1, 2, 1]
[1, 0, 3]
[1, 2, 1]
[1, 3, 2]
[1, 1, 3]
[1, 3, 4]