Java数据结构与算法:最短路径算法

Java数据结构与算法:最短路径算法

大家好,我是免费搭建查券返利机器人赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!

引言

在计算机科学和网络领域,最短路径算法是一类重要的算法,用于寻找两个顶点之间路径权值之和最小的路径。这一算法在路由选择、网络规划等方面有着广泛的应用。本文将介绍最短路径算法的基本概念、常见的实现方式,并通过Java代码演示其应用。

最短路径算法简介

最短路径问题可以分为单源最短路径和多源最短路径两类。其中,Dijkstra算法和Bellman-Ford算法是常用的单源最短路径算法,而Floyd-Warshall算法则是常用的多源最短路径算法。

  1. Dijkstra算法:用于计算图中单个源点到其他所有顶点的最短路径。
  2. Bellman-Ford算法:用于计算图中单个源点到其他所有顶点的最短路径,但可以处理带有负权边的图。
  3. Floyd-Warshall算法:用于计算图中所有顶点之间的最短路径,适用于有向图或无向图。

Dijkstra算法的实现

以下是Dijkstra算法的简单实现,假设图的表示采用邻接矩阵:

import java.util.*;

class ShortestPath {
    private int vertices;
    private int[][] graph;

    public ShortestPath(int vertices) {
        this.vertices = vertices;
        this.graph = new int[vertices][vertices];
    }

    public void addEdge(int source, int destination, int weight) {
        graph[source][destination] = weight;
        graph[destination][source] = weight;
    }

    public int[] dijkstra(int source) {
        int[] distance = new int[vertices];
        Arrays.fill(distance, Integer.MAX_VALUE);
        distance[source] = 0;

        Set<Integer> visited = new HashSet<>();
        PriorityQueue<Node> minHeap = new PriorityQueue<>(Comparator.comparingInt(node -> node.distance));
        minHeap.offer(new Node(source, 0));

        while (!minHeap.isEmpty()) {
            Node currentNode = minHeap.poll();
            int currentVertex = currentNode.vertex;

            if (visited.contains(currentVertex)) {
                continue;
            }

            visited.add(currentVertex);

            for (int neighbor = 0; neighbor < vertices; neighbor++) {
                int edgeWeight = graph[currentVertex][neighbor];
                if (edgeWeight > 0 && !visited.contains(neighbor)) {
                    int newDistance = distance[currentVertex] + edgeWeight;
                    if (newDistance < distance[neighbor]) {
                        distance[neighbor] = newDistance;
                        minHeap.offer(new Node(neighbor, newDistance));
                    }
                }
            }
        }

        return distance;
    }

    private static class Node {
        int vertex;
        int distance;

        public Node(int vertex, int distance) {
            this.vertex = vertex;
            this.distance = distance;
        }
    }
}

public class DijkstraExample {
    public static void main(String[] args) {
        ShortestPath graph = new ShortestPath(6);
        graph.addEdge(0, 1, 2);
        graph.addEdge(0, 2, 4);
        graph.addEdge(1, 2, 1);
        graph.addEdge(1, 3, 7);
        graph.addEdge(2, 4, 3);
        graph.addEdge(3, 4, 1);
        graph.addEdge(3, 5, 5);
        graph.addEdge(4, 5, 2);

        int[] shortestDistances = graph.dijkstra(0);

        System.out.println("Shortest Distances from Source (Vertex 0): " + Arrays.toString(shortestDistances));
    }
}

总结

最短路径算法是图论中的重要内容,涉及到图中两点之间的最短路径问题。本文简要介绍了最短路径问题的概念,并通过Dijkstra算法的Java实现展示了其中一种常用算法。希望本文能够帮助你更好地理解和运用最短路径算法。

  • 17
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 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 =

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值