程序员必备的十大技能(进阶版)之高阶数据结构与算法(三)

简介: 教程来源 http://unbgv.cn/ 本节系统讲解图的核心算法:最短路径(Dijkstra、Bellman-Ford、Floyd-Warshall)、最小生成树(Kruskal、Prim)及拓扑排序(Kahn与DFS实现),涵盖适用条件、时间复杂度与Java代码实现,适用于算法学习与工程实践。

四、图的算法体系

4.1 最短路径算法全解析
Dijkstra算法(非负权图)

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

public class Dijkstra {

    // 标准实现 - 使用优先队列 O((V+E) log V)
    public int[] dijkstra(List<Edge>[] graph, int source) {
        int n = graph.length;
        int[] dist = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[source] = 0;

        // 优先队列:按距离排序
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
        pq.offer(new int[]{source, 0});

        while (!pq.isEmpty()) {
            int[] curr = pq.poll();
            int u = curr[0];
            int d = curr[1];

            if (d > dist[u]) continue;  // 过时的条目,跳过

            for (Edge edge : graph[u]) {
                int v = edge.to;
                int newDist = dist[u] + edge.weight;
                if (newDist < dist[v]) {
                    dist[v] = newDist;
                    pq.offer(new int[]{v, newDist});
                }
            }
        }
        return dist;
    }
}

Bellman-Ford算法(支持负权边,可检测负环)

public class BellmanFord {

    // 时间复杂度 O(VE)
    public int[] bellmanFord(List<Edge>[] graph, int source, boolean[] hasNegativeCycle) {
        int n = graph.length;
        int[] dist = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[source] = 0;

        // 松弛操作,重复 V-1 次
        for (int i = 0; i < n - 1; i++) {
            boolean updated = false;
            for (int u = 0; u < n; u++) {
                if (dist[u] == Integer.MAX_VALUE) continue;
                for (Edge edge : graph[u]) {
                    int v = edge.to;
                    if (dist[u] + edge.weight < dist[v]) {
                        dist[v] = dist[u] + edge.weight;
                        updated = true;
                    }
                }
            }
            if (!updated) break;  // 提前终止
        }

        // 第V次松弛:检测负环
        for (int u = 0; u < n; u++) {
            if (dist[u] == Integer.MAX_VALUE) continue;
            for (Edge edge : graph[u]) {
                int v = edge.to;
                if (dist[u] + edge.weight < dist[v]) {
                    hasNegativeCycle[0] = true;
                    return dist;
                }
            }
        }
        return dist;
    }
}

Floyd-Warshall算法(全源最短路径)

public class FloydWarshall {

    // 时间复杂度 O(V³)
    public int[][] floydWarshall(int[][] graph) {
        int n = graph.length;
        int[][] dist = new int[n][n];

        // 初始化
        for (int i = 0; i < n; i++) {
            System.arraycopy(graph[i], 0, dist[i], 0, n);
        }

        // 动态规划:k 作为中间节点
        for (int k = 0; k < n; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (dist[i][k] != Integer.MAX_VALUE && 
                        dist[k][j] != Integer.MAX_VALUE &&
                        dist[i][k] + dist[k][j] < dist[i][j]) {
                        dist[i][j] = dist[i][k] + dist[k][j];
                    }
                }
            }
        }
        return dist;
    }
}

4.2 最小生成树
Kruskal算法(贪心 + 并查集)

class UnionFind { /* 前面已实现 */ }

class Edge implements Comparable<Edge> {
    int u, v, weight;
    Edge(int u, int v, int weight) {
        this.u = u;
        this.v = v;
        this.weight = weight;
    }
    @Override
    public int compareTo(Edge other) {
        return Integer.compare(this.weight, other.weight);
    }
}

public class Kruskal {

    // 时间复杂度 O(E log E)
    public List<Edge> kruskal(int n, List<Edge> edges) {
        List<Edge> mst = new ArrayList<>();
        Collections.sort(edges);
        UnionFind uf = new UnionFind(n);

        for (Edge edge : edges) {
            if (uf.find(edge.u) != uf.find(edge.v)) {
                uf.union(edge.u, edge.v);
                mst.add(edge);
                if (mst.size() == n - 1) break;
            }
        }
        return mst;
    }
}

Prim算法(优先队列优化)

public class Prim {

    // 时间复杂度 O(E log V)
    public int prim(List<Edge>[] graph) {
        int n = graph.length;
        boolean[] visited = new boolean[n];
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));

        // 从节点0开始
        pq.offer(new int[]{0, 0});
        int totalWeight = 0;
        int edgeCount = 0;

        while (!pq.isEmpty() && edgeCount < n) {
            int[] curr = pq.poll();
            int u = curr[0];
            int weight = curr[1];

            if (visited[u]) continue;

            visited[u] = true;
            totalWeight += weight;
            edgeCount++;

            for (Edge edge : graph[u]) {
                if (!visited[edge.to]) {
                    pq.offer(new int[]{edge.to, edge.weight});
                }
            }
        }
        return totalWeight;
    }
}

4.3 拓扑排序(有向无环图)

public class TopologicalSort {

    // Kahn算法(BFS)
    public List<Integer> kahnTopologicalSort(List<Integer>[] graph) {
        int n = graph.length;
        int[] inDegree = new int[n];

        // 计算入度
        for (int i = 0; i < n; i++) {
            for (int neighbor : graph[i]) {
                inDegree[neighbor]++;
            }
        }

        // 队列存储入度为0的节点
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            if (inDegree[i] == 0) {
                queue.offer(i);
            }
        }

        List<Integer> result = new ArrayList<>();
        while (!queue.isEmpty()) {
            int u = queue.poll();
            result.add(u);

            for (int v : graph[u]) {
                inDegree[v]--;
                if (inDegree[v] == 0) {
                    queue.offer(v);
                }
            }
        }

        // 检查环
        if (result.size() != n) {
            throw new RuntimeException("图中存在环,无法进行拓扑排序");
        }
        return result;
    }

    // DFS方法
    public List<Integer> dfsTopologicalSort(List<Integer>[] graph) {
        int n = graph.length;
        boolean[] visited = new boolean[n];
        boolean[] onStack = new boolean[n];  // 用于检测环
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                if (dfs(i, graph, visited, onStack, stack)) {
                    throw new RuntimeException("图中存在环");
                }
            }
        }

        List<Integer> result = new ArrayList<>();
        while (!stack.isEmpty()) {
            result.add(stack.pop());
        }
        return result;
    }

    private boolean dfs(int v, List<Integer>[] graph, boolean[] visited, 
                        boolean[] onStack, Stack<Integer> stack) {
        visited[v] = true;
        onStack[v] = true;

        for (int neighbor : graph[v]) {
            if (!visited[neighbor]) {
                if (dfs(neighbor, graph, visited, onStack, stack)) {
                    return true;
                }
            } else if (onStack[neighbor]) {
                return true;  // 发现环
            }
        }

        onStack[v] = false;
        stack.push(v);
        return false;
    }
}

来源:
http://htnus.cn/

相关文章
|
移动开发 算法 调度
【贪心算法】一文让你学会“贪心”(贪心算法详解及经典案例)
贪心算法是一种非常常见的算法,它的简单和高效性使其在实际应用中被广泛使用。 贪心算法的核心思想是在每一步都采取当前状态下最优的选择,而不考虑未来可能产生的影响。虽然贪心算法不能保证总是得到最优解,但在很多情况下,它可以获得很好的结果。 本篇文章将介绍贪心算法的基本概念和一些经典应用,以及如何通过贪心算法来解决一些实际问题。希望通过本文的阅读,读者可以对贪心算法有更加深刻的理解,并能够在实际问题中应用贪心算法来得到更好的解决方案。 让我们暴打贪心算法吧!
7231 0
|
关系型数据库 MySQL Windows
mysql彻底卸载干净的5个步骤,超多图超详细保姆级教程最新教程新手小白轻松上手
mysql彻底卸载干净的5个步骤,超多图超详细保姆级教程最新教程新手小白轻松上手
28336 2
|
DataX 数据格式 Java
DataX插件编写指南
DataX 是阿里巴巴集团内被广泛使用的离线数据同步工具/平台,实现包括 MySQL、Oracle、HDFS、Hive、OceanBase、HBase、OTS、ODPS 等各种异构数据源之间高效的数据同步功能。DataX采用了框架 + 插件 的模式,目前已开源,代码托管在github。
14229 1
|
8月前
|
人工智能 安全 API
深度解析 Claude Code 在 Prompt / Context / Harness 的设计与实践
文章内容基于作者个人技术实践与独立思考,旨在分享经验,仅代表个人观点。
4612 75
深度解析 Claude Code 在 Prompt / Context / Harness 的设计与实践
|
6月前
|
XML 人工智能 JSON
为什么AI大模型普遍采用Markdown格式?——技术解读与应用实践
本文深度解析AI大模型普遍采用Markdown格式的原因:其纯文本轻量、语义清晰、容错性强,兼顾人类可读与机器解析;训练数据天然适配,推理稳定高效;且能无缝转换为HTML、PDF等多场景格式,在生成难度、Token效率与生态兼容间实现最优平衡。(239字)
1221 0
|
9月前
|
人工智能 监控 API
2026年OpenClaw量化交易攻略:阿里云+本地部署指南 解锁AI全自动交易逻辑
2026年,AI Agent在交易领域的突破性应用来自OpenClaw(原Clawdbot)——这个具备自主任务规划与执行能力的智能体,以50美元启动资金实现48小时滚雪球至2980美元的惊人战绩,收益率高达5860%。其核心逻辑在于:每10分钟扫描Polymarket近千个预测市场,借助大模型深度推理,交叉验证多维度信息捕捉定价偏差,再通过凯利准则严控单仓位在总资金6%以内,实现低风险高频套利。
4098 5
|
11月前
|
人工智能 程序员 决策智能
2026年智能体(Agent)怎么学?从入门到实战的全景避坑指南
2026年,AI进入“智能体元年”。本文系统解析智能体四大核心架构与Agentic Workflow设计模式,涵盖开发者、产品经理到业务人员的实战路径,助力把握AI代理红利期,实现从工具应用到架构创新的跃迁。
13224 6
|
SQL 监控 关系型数据库
MySQL事务处理:ACID特性与实战应用
本文深入解析了MySQL事务处理机制及ACID特性,通过银行转账、批量操作等实际案例展示了事务的应用技巧,并提供了性能优化方案。内容涵盖事务操作、一致性保障、并发控制、持久性机制、分布式事务及最佳实践,助力开发者构建高可靠数据库系统。
‘conda‘不是内部或外部命令,也不是可运行的程序或批处理文件。
‘conda‘不是内部或外部命令,也不是可运行的程序或批处理文件。
6672 1
‘conda‘不是内部或外部命令,也不是可运行的程序或批处理文件。
|
应用服务中间件 uml
【UML】软件工程中常用图:类图、部署图、时序图、状态图
【UML】软件工程中常用图:类图、部署图、时序图、状态图
4845 1