拓扑排序及其具体实现

一、拓扑排序概述

1.1 什么是拓扑序列和拓扑排序

G = ( V , E ) G=(V,E) G=(V,E) 是一个具有 n n n 个顶点的有向无环图(DAG, Directed Acyclic Graph) V V V 中的顶点序列 ” v 1 , v 2 , … , v n v_1, v_2, \dots, v_n v1,v2,,vn “ 称为一个拓扑序列(topological sequence)。若 < v i , v j > <v_i,v_j> <vi,vj> 是图中的一条边或者从顶点 v i v_i vi 到顶点 v j v_j vj 有路径,则在该拓扑序列中顶点 v i v_i vi 必须排在顶点 v j v_j vj之前。
在一个有向图中找一个拓扑序列的过程称为拓扑排序(topological sort)

拓扑排序只适用于DAG。如果图中存在环,拓扑排序是无法进行的。

1.2 拓扑排序的基本解决思路

拓扑排序的目标是在一个有向无环图中找出一个顶点的排列,使得对于每条有向边 ⟨ u , v ⟩ ⟨u,v⟩ u,v,顶点 u u u 在排列中出现在顶点 v v v 之前。其基本解决思路为:

  1. 从有向图中选择一个没有前驱(即入度为0)的顶点并且输出它
  2. 从图中删去该顶点,并且删去从该顶点发出的全部有向边。
  3. 重复上述两步,直到剩余的图中不再存在没有前驱的顶点为止。

这样操作的结果只要以下两种:

  • 图中全部顶点被输出,即该图中所有顶点都在其拓扑序列中,图中不存在回路
  • 图中顶点未被全部输出,图中存在回路,无法进行拓扑排序。

1.3 应用场景

  • 任务调度:某些任务必须在其他任务之前完成。

  • 编译器中的依赖解析:编译器需要根据代码文件的依赖关系来确定编译顺序。

  • 判断图是否为有向无环图。

二、拓扑排序的常见实现

根据拓扑排序的基本解决思路,常见的实现主要有:

  • 贪心算法,利用队列实现,时间复杂度为 O ( V 2 ) O(V^2) O(V2)
  • 深度优先搜索,利用栈来实现,时间复杂度为 O ( V + E ) O(V+E) O(V+E)

2.1 贪心算法

贪心算法使用了一个队列来实现。其基本步骤如下:

  1. 计算图中每个顶点的入度。
  2. 将所有入度为0的顶点入队列。
  3. 当队列不为空时,执行以下操作:
    • 从队列中取出一个顶点,将其添加到拓扑排序的结果集中。
    • 对该顶点的每一个邻接顶点,将其入度减1。如果入度减为0,将该邻接顶点入队列。
  4. 如果所有顶点都已处理完,返回结果集;否则,说明图中存在环,无法进行拓扑排序。
import java.util.*;

public class TopologicalSortKahn {
    public List<Integer> kahnTopologicalSort(int[][] graph, int numVertices) {
        int[] inDegree = new int[numVertices];  // 记录每个顶点的入度
        List<Integer> topoOrder = new ArrayList<>();  // 存储最终的拓扑排序
        Queue<Integer> queue = new LinkedList<>();  // 队列用于存储入度为0的顶点
        
        // 计算所有顶点的入度
        for (int[] edge : graph) {
            inDegree[edge[1]]++;
        }
        
        // 将所有入度为0的顶点加入队列
        for (int i = 0; i < numVertices; i++) {
            if (inDegree[i] == 0) {
                queue.offer(i);
            }
        }
        
        // 处理队列中的顶点
        while (!queue.isEmpty()) {
            int u = queue.poll();
            topoOrder.add(u);
            
            // 遍历该顶点的邻接顶点,将其入度减1
            for (int[] edge : graph) {
                if (edge[0] == u) {
                    inDegree[edge[1]]--;
                    if (inDegree[edge[1]] == 0) {
                        queue.offer(edge[1]);
                    }
                }
            }
        }
        
        // 如果排序结果包含了所有顶点,则成功完成拓扑排序,否则图中存在环
        if (topoOrder.size() == numVertices) {
            return topoOrder;
        } else {
            throw new IllegalArgumentException("Graph has a cycle, no topological ordering exists.");
        }
    }

    public static void main(String[] args) {
        TopologicalSortKahn topoSort = new TopologicalSortKahn();
        int[][] graph = {{0, 1}, {1, 2}, {2, 3}, {3, 4}};
        int numVertices = 5;
        System.out.println(topoSort.kahnTopologicalSort(graph, numVertices));
    }
}

2.2 深度优先搜索

DFS 的拓扑排序通过递归访问每个顶点。每当一个顶点的所有邻接顶点都已经被访问过时,将该顶点添加到结果集的开头。其基本步骤如下:

  1. 初始化一个布尔数组 visited,用于标记每个顶点是否被访问过。具体状态有:
    • 0:未访问。
    • 1:当前节点正在访问中(即在递归栈中)。
    • 2:该节点及其所有后继节点都已经访问完成。
  2. 使用递归函数 dfs 对每个未访问的顶点进行深度优先搜索,在递归返回时将顶点压入栈 stack 中。在深度优先搜索过程中,如果访问节点已经被访问(即该节点已经压入栈中),说明图中存在环,无法拓扑排序。
  3. 最终,将栈中的顶点依次弹出,形成拓扑排序的结果。
import java.util.*;

public class TopologicalSortDFS {
    public List<Integer> dfsTopologicalSort(int[][] graph, int numVertices) {
        List<Integer> topoOrder = new ArrayList<>();
        int[] visitState = new int[numVertices];  // 0 = 未访问, 1 = 正在访问, 2 = 访问完成
        Stack<Integer> stack = new Stack<>();
        
        // 创建邻接表
        Map<Integer, List<Integer>> adjList = new HashMap<>();
        for (int i = 0; i < numVertices; i++) {
            adjList.put(i, new ArrayList<>());
        }
        for (int[] edge : graph) {
            adjList.get(edge[0]).add(edge[1]);
        }
        
        // 对每个顶点进行DFS
        for (int i = 0; i < numVertices; i++) {
            if (visitState[i] == 0) {
                if (dfs(i, adjList, visitState, stack)) {
                    throw new IllegalArgumentException("Graph has a cycle, no topological ordering exists.");
                }
            }
        }
        
        // 输出结果为逆序的栈
        while (!stack.isEmpty()) {
            topoOrder.add(stack.pop());
        }
        
        return topoOrder;
    }
    
    private boolean dfs(int vertex, Map<Integer, List<Integer>> adjList, int[] visitState, Stack<Integer> stack) {
        visitState[vertex] = 1;  // 标记为正在访问
        for (int neighbor : adjList.get(vertex)) {
            if (visitState[neighbor] == 1) {
                return true;  // 检测到环
            }
            if (visitState[neighbor] == 0) {
                if (dfs(neighbor, adjList, visitState, stack)) {
                    return true;  // 检测到环
                }
            }
        }
        visitState[vertex] = 2;  // 标记为访问完成
        stack.push(vertex);
        return false;
    }

    public static void main(String[] args) {
        TopologicalSortDFS topoSort = new TopologicalSortDFS();
        int[][] graph = {{0, 1}, {1, 2}, {2, 3}, {3, 4}};
        int numVertices = 5;
        System.out.println(topoSort.dfsTopologicalSort(graph, numVertices));
        
        // 测试带有环的图
        int[][] graphWithCycle = {{0, 1}, {1, 2}, {2, 0}};
        try {
            System.out.println(topoSort.dfsTopologicalSort(graphWithCycle, 3));
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

三、Leetcode 题目

207. 课程表 - 力扣(LeetCode):构建邻接表,利用拓扑排序确认有向图中是否存在环。

class Solution {
    List<List<Integer>> edges;
    int[] visited;  // 0 = 未访问, 1 = 正在访问(在栈里), 2 = 访问完成
    boolean ans = true;
    
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        edges = new ArrayList<List<Integer>>();
        visited = new int[numCourses];

        // 构建邻接表
        for(int i = 0; i < numCourses; i++){
            edges.add(new ArrayList<Integer>());
        }
        for(int[] prerequisity : prerequisites){
            edges.get(prerequisity[1]).add(prerequisity[0]);
        }

        // 遍历图中的每个点,判断以该点为起点是否拓扑排序
        for(int course = 0; course < numCourses && ans; ++course){
            if(visited[course] == 0){
                dfs(course);
            }
        }
        return ans;
    }

    // 利用深度优先搜素得到拓扑排序
    public void dfs(int u){
        visited[u] = 1;         // 标记为正在访问
        for(int v : edges.get(u)){
            if(visited[v] == 1){    
                ans = false; // 存在环
                return;
            }
            if( visited[v] == 0){
                dfs(v);
                if(!ans) return;
            }
        }
        visited[u] = 2;        // 标记为访问完成
    }
}

参考资料

拓扑排序及算法实现_拓扑排序算法-优快云博客

《数据结构教程(第五版)》 - 李春葆

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值