用java写一个最短路径算法
时间: 2023-02-20 10:40:09 浏览: 41
您可以使用 Dijkstra 算法来解决最短路径问题。该算法基于贪心策略,通过不断地选择未确定的最短路径节点来实现。在 Java 中,您可以使用优先队列来维护未确定的节点,从而确定最短路径。
以下是 Java 代码的简单实现:
```
import java.util.*;
class Dijkstra {
private int dist[];
private Set<Integer> settled;
private PriorityQueue<Node> pq;
private int V; // Number of vertices
List<List<Node>> adj;
public Dijkstra(int V) {
this.V = V;
dist = new int[V];
settled = new HashSet<Integer>();
pq = new PriorityQueue<Node>(V, new Node());
}
// Function for Dijkstra's Algorithm
public void dijkstra(List<List<Node>> adj, int src) {
this.adj = adj;
for (int i = 0; i < V; i++)
dist[i] = Integer.MAX_VALUE;
// Add source node to the priority queue
pq.add(new Node(src, 0));
// Distance to the source is 0
dist[src] = 0;
while (settled.size() != V) {
// remove the minimum distance node
// from the priority queue
int u = pq.remove().node;
// adding the node whose distance is
// finalized
settled.add(u);
e_Neighbours(u);
}
}
// Function to process all the neighbours
// of the passed node
private void e_Neighbours(int u) {
int edgeDistance = -1;
int newDistance = -1;
// All the neighbors of v
for (int i = 0; i < adj.get(u).size(); i++) {
Node v = adj.get(u).get(i);
// If current node hasn't already been processed
if (!settled.contains(v.node)) {
edgeDistance = v.cost;
newDistance = dist[u] + edgeDistance;
// If new distance is cheaper in cost
if (newDistance < dist[v.node])
dist[v.node] = newDistance;
// Add the current node to the queue
pq.add(new Node(v.node, dist[v.node]));
}
}
}
// Driver code
public static void main(String arg[]) {
int V = 5;
int source =