我正在尝试用Java实现Dijkstra算法。我这样做是使用ArrayList,我知道还有其他数据结构可能更适合这个任务。但是,我想对ArrayLists感到满意,这就是我将要使用的内容。
我有一个对象的ArrayList。这些对象包含多个值,其中一个值是与源节点的距离。如何选择距离值最小的节点?
然后我想将具有最小距离值的顶点的名称设置为String"最小的"。
这是我到目前为止所拥有的。
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;
}
}