LintCode-拓扑排序

给定一个有向图,图节点的拓扑排序被定义为:

  • 对于每条有向边A–> B,则A必须排在B之前  
  • 拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点  

找到给定图的任一拓扑排序

 解法:
 计算所有节点的入度
 选择一个入度为零的节点输出,并将其子节点的入度减1
 循环直到所有节点输出
 
 第一次超时了,后来减少了查表次数和vector的erase操作通过了

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
        map<DirectedGraphNode*, int> numMap;
        for(int i = 0; i < graph.size(); ++i) {
            DirectedGraphNode* node = graph[i];
            
            for(int j = 0; j < node->neighbors.size(); ++j) {
                DirectedGraphNode* child = node->neighbors[j];
                auto it = numMap.find(child);
                if(it != numMap.end()) {
                    it->second += 1;
                }else {
                    numMap[child] = 1;
                }
            }
        }
    
        vector<DirectedGraphNode*> r;
        int base = 0;
        while(base < graph.size()) {
            for(int i = base; i < graph.size(); ++i) {
                DirectedGraphNode* node = graph[i];
                auto it = numMap.find(node);
                if(it == numMap.end() || it->second == 0) {
                    DirectedGraphNode* tmp = graph[base];
                    graph[base] = node;
                    graph[i] = tmp;
                    ++base;
                    r.push_back(node);
                    for(int j = 0; j < node->neighbors.size(); ++j) {
                        numMap[node->neighbors[j]] -= 1;
                    }
                    break;
                }
            }
        }
        
        return r;
    }

};

    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/zaqwsx20/article/details/52668295
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞