【发布时间】:2018-03-03 17:24:24
【问题描述】:
我有一个graph 实现。我的图表类如下所示:
public class Graph<V> {
private HashMap<V, ArrayList<Edge<V>>> adjacencyList;
/**
* This list holds all the vertices so that we can iterate over them in the
* toString function
*/
private ArrayList<V> vertexList;
private boolean directed;
public Graph(boolean isDirected) {
directed = isDirected;
adjacencyList = new HashMap<V, ArrayList<Edge<V>>>();
vertexList = new ArrayList<V>();
}
}
我的驱动程序类也有一个方法,用于计算从另一个顶点开始的最短路径。它工作得很好,并显示了从一个源顶点到所有其他顶点的最短路径权重:
public static <V> HashMap<V, ArrayList<Sehir>> dijkstraShortestPath(Graph<V> graph, V source, V son) {
HashMap<V, Double> distances = new HashMap<V, Double>();
HashMap<V, ArrayList<Sehir>> path = new HashMap<V, ArrayList<Sehir>>();//This is not working!
//ArrayList<Sehir> arrList = new ArrayList<>();
ArrayList<V> queue = new ArrayList<V>();
ArrayList<V> visited = new ArrayList<V>();
queue.add(0, source);
distances.put(source, 0.0);
path.put(source, new ArrayList<>());
while (!queue.isEmpty()) {
V currentVertex = queue.remove(queue.size() - 1);
if(path.get(currentVertex)==null){
path.put(currentVertex, new ArrayList<>());
}
// to save time we initialize all the distances to infinity as we go
if (distances.get(currentVertex) == null) {
distances.put(currentVertex, Double.POSITIVE_INFINITY);
}
// if(distances.get(currentVertex))
for (V adjacentVertex : graph.getAdjacentVertices(currentVertex)) {
if (distances.get(adjacentVertex) == null) {
distances.put(adjacentVertex, Double.POSITIVE_INFINITY);
}
// if (!graph.getEdgeBetween(currentVertex,
// adjacentVertex).isGidebilirMi()) {
// // System.out.println(graph.getEdgeBetween(currentVertex,
// // adjacentVertex).toString());
// distances.put(adjacentVertex, Double.POSITIVE_INFINITY);
// }
// if the distance between the source and the adjacent vertex is
// greater than the distance between the source and the current
// vertex PLUS the weight between the current and adjacent
// vertex, then we have found a shorter path than already
// existed
if (true) {
if (distances.get(adjacentVertex) > graph.getDistanceBetween(currentVertex, adjacentVertex)
+ distances.get(currentVertex)) {
distances.put(adjacentVertex,
graph.getDistanceBetween(currentVertex, adjacentVertex) + distances.get(currentVertex));
path.get(currentVertex).add((Sehir) adjacentVertex);
}
}
if (!visited.contains(adjacentVertex) && !queue.contains(adjacentVertex)) {
queue.add(0, adjacentVertex);
}
}
visited.add(currentVertex);
}
// since the above statments only added the vertices as needed,
// verticies that are completely unconnected to the source are not added
// yet, so this adds them now
for (V v : graph.getVertexList()) {
if (!distances.containsKey(v)) {
distances.put(v, Double.POSITIVE_INFINITY);
}
}
return path;
}
在这里,如果我返回 distances,它可以正常工作。但是 Path HashMap 没有存储关于路径的正确信息。我怎样才能解决这个问题?我想获取路径,例如对象arrayList。顺便说一句,“Sehir”的意思是“城市”,这是我在 Graph 上的对象。
【问题讨论】:
标签: java algorithm graph shortest-path dijkstra