【发布时间】:2013-11-15 22:54:40
【问题描述】:
我正在实现代码以在directed graph 中获取短路路径,如下所示,使用Dijkstra's algorithm?
我的问题是
如何为顶点定义
adjacency list? 在下面我当前的代码中,我只考虑了邻接列表部分的传出边缘如果图中存在循环模式,Dijkstra 的算法是否会失败?比如ABD在下面形成一个循环
- 如果一个顶点没有出边,则没有以该顶点为源的最短路径,例如:对于下图,如果我想找到从 F 到 A 的最短路径,则没有。 Dijsktra'a 算法应该解决这个问题吗?
我已经实现了 Dijsktra 的算法,但我没有在此处粘贴该代码。在澄清了这些疑虑之后,我将针对 Dijkstra 的实施问题发表一个单独的问题。
我当前的 Vertex、Edge 和 Graph 代码如下。如您所见,我已经为上面的图像定义了顶点和邻接列表。如果 adjcacency 列表正确,请通过您的 cmets。 例如:顶点 F 没有邻接表,因为它没有出边。
class Vertex implements Comparable<Vertex>
{
public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;
public Vertex(String argName) { name = argName; }
public String toString() { return name; }
public int compareTo(Vertex other)
{
return Double.compare(minDistance, other.minDistance);
}
}
class Edge
{
public final Vertex target;
public final double weight;
public Edge(Vertex argTarget, double argWeight)
{ target = argTarget; weight = argWeight; }
}
public class Graph {
public static void main(String[] args) {
Vertex A = new Vertex("A");
Vertex B = new Vertex("B");
Vertex C = new Vertex("C");
Vertex D = new Vertex("D");
Vertex E = new Vertex("E");
Vertex F = new Vertex("F");
Vertex G = new Vertex("G");
A.adjacencies = new Edge[]{ new Edge(B, 1)};
B.adjacencies = new Edge[]{ new Edge(C, 3), new Edge(D, 2)};
C.adjacencies= new Edge[]{new Edge(D, 1),new Edge(E, 4)};
D.adjacencies= new Edge[]{new Edge(E, 2),new Edge(A, 2) };
E.adjacencies= new Edge[]{new Edge(F, 3) };
//F.adjacencies= null;
G.adjacencies= new Edge[]{new Edge(D, 1)};
}
}
【问题讨论】:
标签: graph dijkstra directed-graph adjacency-list