Java语言实现最短路径算法(Shortest Path)

 Java语言实现最短路径算法(Shortest Path)在Java中实现最短路径算法,可以选择经典的Dijkstra算法。Dijkstra算法是一种用于计算加权图中单源最短路径的贪心算法。下面是一个简单的Dijkstra算法实现示例:

import java.util.*;

public class Dijkstra {

    static class Edge {
        int target;
        int weight;

        Edge(int target, int weight) {
            this.target = target;
            this.weight = weight;
        }
    }

    static class Graph {
        int vertices;
        LinkedList<Edge>[] adjacencyList;

        Graph(int vertices) {
            this.vertices = vertices;
            adjacencyList = new LinkedList[vertices];
            for (int i = 0; i < vertices; i++) {
                adjacencyList[i] = new LinkedList<>();
            }
        }

        void addEdge(int source, int target, int weight) {
            adjacencyList[source].add(new Edge(target, weight));
            adjacencyList[target].add(new Edge(source, weight));  // 如果是有向图,则去掉这一行
        }

        void dijkstra(int startVertex) {
            boolean[] visited = new boolean[vertices];
            int[] distances = new int[vertices];
            Arrays.fill(distances, Integer.MAX_VALUE);
            distances[startVertex] = 0;

            PriorityQueue<Edge> pq = new PriorityQueue<>(vertices, Comparator.comparingInt(e -> e.weight));
            pq.add(new Edge(startVertex, 0));

            while (!pq.isEmpty()) {
                Edge edge = pq.poll();
                int vertex = edge.target;

                if (visited[vertex]) continue;
                visited[vertex] = true;

                LinkedList<Edge> edges = adjacencyList[vertex];
                for (Edge e : edges) {
                    int target = e.target;
                    int weight = e.weight;

                    if (!visited[target] && distances[vertex] + weight < distances[target]) {
                        distances[target] = distances[vertex] + weight;
                        pq.add(new Edge(target, distances[target]));
                    }
                }
            }

            printShortestPaths(startVertex, distances);
        }

        void printShortestPaths(int startVertex, int[] distances) {
            System.out.println("Vertex\tDistance from Source " + startVertex);
            for (int i = 0; i < vertices; i++) {
                System.out.println(i + "\t\t" + distances[i]);
            }
        }
    }

    public static void main(String[] args) {
        int vertices = 6;
        Graph graph = new Graph(vertices);
        graph.addEdge(0, 1, 4);
        graph.addEdge(0, 2, 3);
        graph.addEdge(1, 2, 1);
        graph.addEdge(1, 3, 2);
        graph.addEdge(2, 3, 4);
        graph.addEdge(3, 4, 2);
        graph.addEdge(4, 5, 6);

        graph.dijkstra(0);
    }
}

这个示例中,我们创建了一个包含6个顶点的图,并添加了一些边。然后,我们从顶点0开始运行Dijkstra算法,计算并打印出从顶点0到所有其他顶点的最短路径距离。

Java实现最短路径算法,你可以使用经典的Dijkstra算法或者A*算法。这里我给你一个使用Dijkstra算法的示例代码: ```java import java.util.*; public class DijkstraAlgorithm { private int V; private int[][] graph; public DijkstraAlgorithm(int[][] graph) { this.V = graph.length; this.graph = graph; } public int[] findShortestPath(int source) { int[] dist = new int[V]; // 存储源节点到各个节点的最短距离 boolean[] visited = new boolean[V]; // 标记节点是否已被访问 Arrays.fill(dist, Integer.MAX_VALUE); // 初始化距离为无穷大 dist[source] = 0; // 源节点到自身的距离为0 for (int count = 0; count < V - 1; count++) { int u = findMinimumDistance(dist, visited); visited[u] = true; for (int v = 0; v < V; v++) { if (!visited[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) { dist[v] = dist[u] + graph[u][v]; } } } return dist; } private int findMinimumDistance(int[] dist, boolean[] visited) { int minDist = Integer.MAX_VALUE; int minIndex = -1; for (int v = 0; v < V; v++) { if (!visited[v] && dist[v] <= minDist) { minDist = dist[v]; minIndex = v; } } return minIndex; } public static void main(String[] args) { int[][] graph = { {0, 4, 0, 0, 0, 0, 0, 8, 0}, {4, 0, 8, 0, 0, 0, 0, 11, 0}, {0, 8, 0, 7, 0, 4, 0, 0, 2}, {0, 0, 7, 0, 9, 14, 0, 0, 0}, {0, 0, 0, 9, 0, 10, 0, 0, 0}, {0, 0, 4, 14, 10, 0, 2, 0, 0}, {0, 0, 0, 0, 0, 2, 0, 1, 6}, {8, 11, 0, 0, 0, 0, 1, 0, 7}, {0, 0, 2, 0, 0, 0, 6, 7, 0} }; DijkstraAlgorithm dijkstra = new DijkstraAlgorithm(graph); int[] shortestDistances = dijkstra.findShortestPath(0); System.out.println("最短路径:"); for (int i = 1; i < shortestDistances.length; i++) { System.out.println("从节点 " + source + " 到节点 " + i + " 的最短距离为:" + shortestDistances[i]); } } } ``` 这个示例代码使用邻接矩阵来表示图,其中图的顶点数由变量 V 来表示,图的边权重由二维数组 graph 来表示。你可以根据自己的需求修改图的结构。 在示例代码中,`findShortestPath` 方法使用了 Dijkstra 算法来计算从源节点到其他所有节点的最短路径。`main` 方法展示了如何使用这个算法来计算最短路径并输出结果。 希望这个示例代码能帮助到你!如果你对其他算法或者实现有疑问,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值