繁体   English   中英

Java-在图中找到最短路径

[英]Java - Finding the shortest path in a graph

因此,我正在尝试实现Floyd Warshalls算法以在图中找到最短路径。 我正在从如下所示的文本文件中读取值:

Location1 0 0 0 
Location2 5 0 0 
Location3 5 5 0 
Location4 0 5 0

然后,使用此类将这些值存储在哈希表中: http : //algs4.cs.princeton.edu/34hash/SeparateChainingHashST.java.html

这是我到目前为止的内容:

public class Edge {

    private String location;
    private int point1;
    private int point2;
    private int point3;

    public Edge( In in ) {
        n = in.readInt();
        this.location = location;
        this.point1 = point1;
        this.point2 = point2;
        this.point3 = point3;
        int [][] G = new int [n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++){
                G[i][j] = in.readInt();
            }
        }

        int V = G.length;
        int dist[][] = new int [V][V];

        for (int k = 0; k < n; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
                }
            }
        }
    }

问题是我不确定我是否正确读取了这些值,并且我不知道如何将这些值存储在哈希表中,然后将它们放入2d数组中以与Warshall算法一起使用。 这是我的main方法:

 public static void main(String[] args) {
      In in = new In( args[0] );
      int T = in.readInt();
      for (int t=1; t<=T; t++) {
         System.out.println("Case " + t + ":") ;
         Edge w = new Edge( in );
         int Q = in.readInt();
         for (int i=0; i<Q; i++) {
            String p1s = in.readString();
            String p2s = in.readString();
         }
      }
   }
}

这是In类: http : //algs4.cs.princeton.edu/12oop/In.java.html

我建议您使用Djikstra的算法来查找最短路径。 这是一些实现它的伪代码

function Dijkstra(Graph, source):

      create vertex set Q

      for each vertex v in Graph:             // Initialization
          dist[v] ← INFINITY                  // Unknown distance from source to v
          prev[v] ← UNDEFINED                 // Previous node in optimal path from source
          add v to Q                          // All nodes initially in Q (unvisited nodes)

      dist[source] ← 0                        // Distance from source to source

      while Q is not empty:
          u ← vertex in Q with min dist[u]    // Source node will be selected first
          remove u from Q 

          for each neighbor v of u:           // where v is still in Q.
              alt ← dist[u] + length(u, v)
              if alt < dist[v]:               // A shorter path to v has been found
                  dist[v] ← alt 
                  prev[v] ← u 

      return dist[], prev[]

您需要这样的东西:

public static void floydwarshall(int[][]path){
    for(int k=0;k<path.length;k++){
      for(int i=0;i<path.length;i++){
        for(int j=0;j<path.length;j++){
          path[i][j]=Math.min(path[i][j],path[i][k]+path[k][j]);
        }
      }
    }
  }

暂无
暂无

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

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