I am attempting to implement Dijkstra's Algorithm with Java. I am doing so using an ArrayList, and I know that there are other data structures that might be better suited to this task. However, I want to get comfortable with ArrayLists, so that's what I'll be using.
I have an ArrayList of Objects. These objects contain several values, one of which is the distance from the source node. How can I select the node that has the smallest distance value?
I want to then set the name of the vertex that had the smallest distance value to the String "smallest".
Here is what I have so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class Graph
{
ArrayList<Vertex> vertexObjects = new ArrayList<Vertex>();
ArrayList<Edge> edgeObjects = new ArrayList<Edge>();
ArrayList<Vertex> visitedObjects = new ArrayList<Vertex>();
ArrayList<Vertex> unvisitedObjects = new ArrayList<Vertex>();
int numVertices = 0;
public void readFile()
{
try {
Scanner s = new Scanner(new File("graph.txt"));
String sameVertex = "";
while (s.hasNext()) {
String preVertex = s.next();
String postVertex = s.next();
String distance = s.next();
Edge temp = new Edge(preVertex, postVertex, distance);
edgeObjects.add(temp);
if (!(preVertex.equals(sameVertex)))
{
Vertex herp = new Vertex(preVertex, Double.POSITIVE_INFINITY, false, null);
vertexObjects.add(herp);
sameVertex = preVertex;
numVertices++;
}
}
} catch (FileNotFoundException e) {
System.out.println("I can't find that file!");
}
}
public void Dijkstra(String startVertex, String endVertex)
{
// Change the distance of the startVertex to 0 and all others to infinity.
for (int i = (numVertices-1); i >= 0; i--)
{
if (vertexObjects.get(i).vertexName.equals(startVertex))
{
vertexObjects.get(i).distance = 0;
} else {
vertexObjects.get(i).distance = Double.POSITIVE_INFINITY;
}
unvisitedObjects.add(vertexObjects.get(i));
}
String currentVertex = startVertex;
//Set the node with lowest distance value to Current Status
while( unvisitedObjects.size() != 0) {
{
//set current node to vertex with shortest distance
string smallest;
for (int j = (vertexObjects.size()-1); j >= 0; j++) {
if (vertexObjects.get(j).distance < 0) {
smallest = vertexObjects.get(j).distance;
}
}
}
}
}
public class Vertex
{
public String vertexName;
public double distance;
public boolean visitedStatus;
public String previousVertex;
public Vertex(String vertexName, double distance, boolean visitedStatus, String previousVertex)
{
this.vertexName = vertexName;
this.distance = distance;
this.visitedStatus = visitedStatus;
this.previousVertex = previousVertex;
}
public String toString()
{
String d;
if (this.visitedStatus = false)
{
d = "unvisited";
} else {
d = "visited";
}
String s = "Vertex " + vertexName + " is " + d + "and is " + distance + " away from " + previousVertex + ".";
return s;
}
}