【发布时间】:2015-10-15 08:20:41
【问题描述】:
所以我需要使用 Java Dijkstra 算法。我发现here 是 Dijkstra 的一个工作示例。但就我而言,我有大约 5000 个顶点。我得到错误:方法 main(String[]) 的代码超出了 65535 字节限制。 stackoverflow 上有一些这样的主题,但我找不到如何解决这个问题的实现。谁能给我一些关于如何解决这个问题的代码..
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
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 Dijkstra
{
public static void computePaths(Vertex source)
{
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies)
{
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU ;
v.previous = u;
vertexQueue.add(v);
}
}
}
}
public static List<Vertex> getShortestPathTo(Vertex target)
{
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}
public static void main(String[] args)
{
// mark all the vertices
Vertex X1 = new Vertex("A");
//...till Vertex X5000..
// set the edges and weight
X1.adjacencies = new Edge[]{ new Edge(X2, 8) };
//...till X5000.adjacencies...
computePaths(X1); // run Dijkstra
System.out.println("Distance to " + X5 + ": " + X5.minDistance);
List<Vertex> path = getShortestPathTo(X5);
System.out.println("Path: " + path);
}
}
编辑
我正在尝试从 MySQL 表中获取数据,但在声明顶点时遇到问题。
String query = "SELECT * FROM coordinates";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next())
{
int id = rs.getInt("id");
String vert = Integer.toString(id);
//Which approach will work?
Vertex vert = new Vertex(vert);
}
st.close();
【问题讨论】: