拓扑排序(BFS,DFS)

本文介绍了使用宽度优先搜索(BFS)和深度优先搜索(DFS)两种方法来实现图的拓扑排序,并提供了具体的代码示例。通过计算节点的入度进行宽度优先遍历,以及递归地先处理子节点再处理父节点的方式完成深度优先遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述
我们用两种方法来做这道题。

BFS

宽度优先搜索,是说我们每次把没有父亲节点的节点打印。具体操作可以是计算所有节点的入度。将入度为0的节点输出,同时将输出节点的儿子的入度减去一。我们用队列维持入度为0的节点集合。

/**
 * Definition for Directed graph.
 * struct DirectedGraphNode {
 *     int label;
 *     vector<DirectedGraphNode *> neighbors;
 *     DirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    /**
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */
    vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) {
        // write your code here
        vector<int> indegree(graph.size(),0);


        for(auto node:graph){
            for(int i = 0; i < node->neighbors.size(); ++i){
                indegree[node->neighbors[i]->label]++;
            }
        }

        queue<DirectedGraphNode*> que;
        for(int i = 0; i < indegree.size(); ++i){
            if(indegree[i] == 0) que.push(graph[i]);
        }
        vector<DirectedGraphNode *> res;
        while(!que.empty()){
            DirectedGraphNode *temp = que.front();
            for(auto pi:temp->neighbors){
                indegree[pi->label]--;

                if(indegree[pi->label] == 0) que.push(graph[pi->label]);
            }
            que.pop();
            res.push_back(temp);
        }
        return res;
    }
};

DFS

深度优先搜索则是一旦我们要输出一个节点,则把它的父亲全部输出即可。考虑到我们的数据结构是记录每个节点的儿子节点,所以我们这样考虑:
一旦要输出一个节点,先把儿子节点全部输出;最后reverse即可。
创建childinres布尔数组是为了查询O(1)。《—–感谢roommate

/**
 * Definition for Directed graph.
 * struct DirectedGraphNode {
 *     int label;
 *     vector<DirectedGraphNode *> neighbors;
 *     DirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    /**
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */


    void dfs(vector<DirectedGraphNode*> &res, vector<DirectedGraphNode*>& graph, int target, vector<bool>& targetinres){
        if(targetinres[target]) return;
        //cout<<target<<endl;
        for(auto node:graph[target]->neighbors)
            dfs(res,graph,node->label,targetinres);
        res.push_back(graph[target]);
        targetinres[target] = true;
    }

    vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) {
        // write your code here
        vector<DirectedGraphNode*> res;
        vector<bool> targetinres(graph.size(),false);
        for(int i = 0; i < graph.size(); ++i){
            dfs(res,graph,i,targetinres);
        }
        reverse(res.begin(),res.end());
        return res;
    }

};
### BFSDFS 算法的区别及使用场景 BFS(广度优先搜索)和 DFS(深度优先搜索)是两种常见的图遍历算法,它们在思想、实现方式以及适用场景上存在显著差异。 #### 1. **基本思想** - **BFS** 是一种逐层扩展的搜索方式,从起始节点出发,优先访问距离当前节点最近的节点。这种特性使得 BFS 具有最短路径性质,适用于寻找无权图中的最短路径[^2]。 - **DFS** 是一种沿着路径深入的搜索方式,从起始节点出发,尽可能深地探索每个分支,直到无法继续前进时才回溯。这种特性使得 DFS 更适合探索所有可能的路径。 #### 2. **数据结构** - **BFS** 使用队列(Queue)来管理待访问的节点,确保先访问的节点的邻居节点也会优先被访问。 - **DFS** 使用栈(Stack)或递归实现,递归方式更为常见,但容易导致栈溢出。 #### 3. **时间与空间复杂度** - **BFS** 和 **DFS** 的时间复杂度均为 $O(V + E)$,其中 $V$ 是顶点数,$E$ 是边数。 - **BFS** 的空间复杂度通常较高,因为它需要存储每一层的所有节点;而 **DFS** 的空间复杂度取决于递归深度,通常在树的深度较小时表现更好。 #### 4. **适用场景** - **BFS** 更适合以下情况: - 寻找无权图中的最短路径。 - 层次遍历问题,例如按层打印二叉树。 - 需要优先访问距离较近的节点的问题,例如社交网络中查找最近的朋友。 - **DFS** 更适合以下情况: - 探索所有可能的路径,例如迷宫问题。 - 需要回溯的场景,例如图的连通性判断。 - 深度优先的特性使得它在某些问题中更容易实现,例如拓扑排序、判断图中是否存在环。 #### 5. **示例代码** 以下是 **BFS** 和 **DFS** 的简单实现示例: **BFS 实现** ```python from collections import deque def bfs(graph, start): visited = set() queue = deque([start]) visited.add(start) while queue: node = queue.popleft() print(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) ``` **DFS 实现** ```python def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) print(start) for neighbor in graph[start]: if neighbor not in visited: dfs(graph, neighbor, visited) ``` #### 6. **总结** - **BFS** 更适合寻找最短路径或层次遍历问题,而 **DFS** 更适合探索所有可能路径或需要回溯的场景。 - **BFS** 使用队列实现,**DFS** 使用栈或递归实现。 - 在实际应用中,选择哪种算法取决于具体问题的需求和数据结构的特性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值