所以我试图实现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();
}
}
}
}
答案 0 :(得分:0)
我建议您使用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[]
答案 1 :(得分:0)
你需要这样的东西:
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]);
}
}
}
}