[英]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();
}
}
}
}
我建議您使用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.