lintcode:Topological Sorting

本文介绍了一种解决有向图拓扑排序的方法,并提供了一个具体的C++实现方案。通过递归深度优先搜索的方式,文章详细阐述了如何找出图中的拓扑顺序,使得对于每一条有向边 A->B,节点A都在节点B之前。

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

 Topological Sorting
07:18

Given an directed graph, a topological order of the graph nodes is defined as follow:

  • For each directed edge A -> B in graph, A must before B in the order list.
  • The first node in the order can be any node in the graph with no nodes direct to it.

Find any topological order for the given graph.

 Notice

You can assume that there is at least one topological order in the graph.

For graph as follow:


顺便贴一个topology的视频:https://www.youtube.com/watch?v=ddTC4Zovtbc


/**
 * Definition for Directed graph.
 * struct DirectedGraphNode {
 *     int label;
 *     vector<DirectedGraphNode *> neighbors;
 *     DirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
    
private:
    void topSortHelper(DirectedGraphNode* curNode, stack<DirectedGraphNode*> &auxStack, set<int> &visited)
    {
        visited.insert(curNode->label);
        
        for (int i=0; i<curNode->neighbors.size(); i++)
        {
            if (visited.find(curNode->neighbors[i]->label) == visited.end()) 
            {
                topSortHelper(curNode->neighbors[i], auxStack, visited);
            }
        }
        auxStack.push(curNode);//当这个节点已经visit 过它所有的子节点的之后,就把它发到stack中,所以stack的最上层肯定是依赖性最小的,食物链最高的节点
    }
    
    
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
        
        set<int> visited;
        stack<DirectedGraphNode*> auxStack;
        
        for (int i=0; i<graph.size(); i++)
        {
            if (visited.find(graph[i]->label) == visited.end())
            {
                topSortHelper(graph[i], auxStack, visited);
            }
        }
        
        vector<DirectedGraphNode*> retVtr;
        while (auxStack.size() > 0)
        {
            retVtr.push_back(auxStack.top());
            auxStack.pop();
        }
        
        return retVtr;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值