图的深度优先遍历-两个顶点之间的最短路径

题目:
求解两个顶点之间的最短路径,比如如下的一张图:
在这里插入图片描述
该图对应的点边权重值:

5 8
1 2 2
1 5 10
2 3 3
2 5 7
3 1 4
3 4 4 c
4 5 5
5 3 3

第一行代表5个点,8个边,后面每一行代表两个顶点的连接,以及该边上的权重值,比如第二行是1,2有一条边,边上的权重是2.

其解题思路是通过改点的深度优先遍历计算到达指定顶点的距离,并通过回退不断更新两点之间的距离取最小值,其过程如下:
在这里插入图片描述

Java代码实现如下所示:


package graph.path;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TwoPointShortestPath {

    private int[][] matrix;
    private int V;
    private int E;

    private boolean[] visited;

    private int shortestPath;
    public static void main(String[] args) throws Exception {
        TwoPointShortestPath twoPointShortestPath = new TwoPointShortestPath();
        twoPointShortestPath.buildGraph();
        int shortestPath1 = twoPointShortestPath.findShortestPath(1,5);

        System.out.println(shortestPath1);

    }

    private void buildGraph() throws Exception {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("src/main/resources/graph/gpath.txt"));
        String s = bufferedReader.readLine();
        V = Integer.parseInt(s.trim().split(" ")[0]);
        E = Integer.parseInt(s.trim().split(" ")[1]);

        matrix = new int[V][V];
        visited = new boolean[V];
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                matrix[i][j] = i == j ? 0 : Integer.MAX_VALUE;
            }
        }
        while ((s = bufferedReader.readLine()) != null) {
            String[] splitStr = s.trim().split(" ");
            matrix[Integer.parseInt(splitStr[0]) - 1][Integer.parseInt(splitStr[1]) - 1] = Integer.parseInt(splitStr[2]);
        }
    }


    private int findShortestPath(int start, int end) {
        // 初始化
        shortestPath = matrix[start-1][end-1];
        dfs(start-1, end - 1, 0);

        return shortestPath;
    }

    private void dfs(int start, int end, int path) {

        // 特殊处理剪纸,在递归下去只会更大,没意义
        if (path > shortestPath) {
            return;
        }

        if (start == end) {
            shortestPath = path;
            return;
        }

        for (int i = 0; i < V; i++) {
            if (start!= i && matrix[start][i] != Integer.MAX_VALUE && !visited[i]) {
                visited[i] = true;
                dfs(i, end, path + matrix[start][i]);
                visited[i] = false;
            }
        }

    }

}

结果如下:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值