简体   繁体   中英

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. 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
  • index2: the index I want to find the shortest path to.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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