I am implementing the code to get the shorted path in a directed graph
as shown below using Dijkstra's algorithm
?
my question is
how to define the
adjacency list
for a vertex? in my current code below, I have considered only the outgoing edges to the part of the adjacency listDoes Dijkstra's alogithm fail if there is a cyclic pattern with in the graph? for example, ABD forms a cycle below
- if there is no outgoing edges from a vertex, then there is no shortest path from that vertex as the source, example: for the graph below, If I want to find the shortest path from F to A, there is none. should Dijsktra'a algorithm takes care of that?
I have implemented Dijsktra's algorithm, but I am not pasting that code here. After clarifying these doubts, I will post a seperate question on my problems with Dijkstra's implementation.
my current code for Vertex, Edge and Graph is below. As you can notice, I have defined the vertex and adjacency list for the above image. please pass your comments if the adjcacency list is correct. eg: vertex F has no adjacency list as there are no outgoing edges from it.
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)};
}
}