Lintcode:拓扑排序(深度优先搜索,广度优先搜索)

//广度优先搜索(BFS)

vector topSort(vector graph) {  
        vector ret;  
        if(graph.empty())  
            return ret;  
          
        map in; //in为入度  
        queue   s;  //保存入度为零的节点  
        for(auto e:graph){  
            for(auto i:e->neighbors)  
                ++in[i];              //记录每个节点的入度  
        }  
          
        for(auto e:graph)  
           if(0==in[e])  
               s.push(e);         //入度为零的节点入栈  
          
        while(!s.empty()){        //BFS遍历,搜寻入度为零的节点  
            DirectedGraphNode* cur=s.front();  
            s.pop();             //当前节点出栈时,它的相邻节点入度都减一  
            ret.push_back(cur);     
            for(auto e:cur->neighbors){  
                if(--in[e]==0)    //减一后为零则入栈  
                    s.push(e);  
            }  
        }         
        return ret;  
    }  
//深度优先搜索(DFS)

bool search(vector &result, DirectedGraphNode* node)
    {
        for(auto p: result)
        {
            if(p == node)
              return 1;
        }
        return 0;
    }
    //DFS
    void dfs(DirectedGraphNode* graph, vector &result)
    {
        for(auto childgraph: graph->neighbors)
        {
            if(!search(result,childgraph))
             dfs(childgraph, result);
        }
        result.push_back(graph);
    }
    
    vector topSort(vector graph) {
        // write your code here
        vector result;
        for(auto node : graph)
        {
          if(!search(result,node))
           dfs(node, result);
        }
        reverse(result.begin(),result.end());
        return result;
    }



你可能感兴趣的:(lintcode)