简体   繁体   English

使用边列表实现最短路径算法 Java

[英]Implementing shortest path algorithm Java with list of edges

I am writing a method in Java to find the shortest path between two nodes in a graph.我正在 Java 中编写一个方法来查找图中两个节点之间的最短路径。 The parameters are the following参数如下

  • an array list of "edges": objects containing the index of the source node of the edge and the index of the destination node of the edge “边”的数组列表:包含边源节点索引和边目标节点索引的对象
  • index1: the first index index1:第一个索引
  • index2: the index I want to find the shortest path to. index2:我想找到最短路径的索引。

I have written the following code:我写了以下代码:

    public static String shortestDistance(List<edge> edges, int index1, int index2) {
    String shortest = "";
        for (int i = 0; i < edges.size(); i++) {
            edge e = edges.get(i);
            if (e.src == index1) {
                  //shortest path here
                shortest = shortest + e.src + ", ";

            }
        }
        return shortest;
}

My goal is to return a string containing a list of the shortest possible path.我的目标是返回一个包含最短路径列表的字符串。 How do I begin to implement an algorithm to search for the shortest path between the two indexes?我如何开始实施一种算法来搜索两个索引之间的最短路径?

You can use Breadth First Search to find the shortest path from one node to another in a graph.您可以使用广度优先搜索来查找图中从一个节点到另一个节点的最短路径。

https://www.baeldung.com/java-breadth-first-search https://www.baeldung.com/java-breadth-first-search

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM