锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

lintcode:Topological Sorting

时间:2022-08-03 17:19:00 sitemap ddtc114eca数字三极管

Topological Sorting

07:18

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

  • For each directed edgeA -> Bin 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 neighbors;
 *     DirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
    
private:
    void topSortHelper(DirectedGraphNode* curNode, stack &auxStack, set &visited)
    {
        visited.insert(curNode->label);
        
        for (int i=0; ineighbors.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 topSort(vector graph) {
        // write your code here
        
        set visited;
        stack auxStack;
        
        for (int i=0; ilabel) == visited.end())
            {
                topSortHelper(graph[i], auxStack, visited);
            }
        }
        
        vector retVtr;
        while (auxStack.size() > 0)
        {
            retVtr.push_back(auxStack.top());
            auxStack.pop();
        }
        
        return retVtr;
    }
};


相关文章