• LintCode Topological Sorting


    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.
    Have you met this question in a real interview? Yes
    Example
    For graph as follow:
    picture
    The topological order can be:
    [0, 1, 2, 3, 4, 5]
    [0, 2, 3, 1, 5, 4]
    ...
    Note
    You can assume that there is at least one topological order in the graph.
    Challenge
    Can you do it in both BFS and DFS?

    首先给出一个DFS的,这个以前倒是没这么写

    /**
     * Definition for Directed graph.
     * struct DirectedGraphNode {
     *     int label;
     *     vector<DirectedGraphNode *> neighbors;
     *     DirectedGraphNode(int x) : label(x) {};
     * };
     */
    class Solution {
    private:
        unordered_set<DirectedGraphNode*> visited;
        
    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
            visited.clear();
            
            vector<DirectedGraphNode*> path;
            
            for (auto node : graph) {
                dfs(node, path);
            }
            reverse(path.begin(), path.end());
            
            return path;
        }
        
        void dfs(DirectedGraphNode* node, vector<DirectedGraphNode*>& path) {
            if (visited.count(node) > 0) {
                return;
            }
            visited.insert(node);
            
            for (auto n : node->neighbors) {
                dfs(n, path);
            }
            
            path.push_back(node);
        }
    };
    
  • 相关阅读:
    经典SQL语句大全
    C# 在子线程中创建不会阻塞执行窗体
    win7 C# winForm编程 savefiledialog 不能弹出保存窗体
    什么是AJAX技术及其常识
    C++安装失败解决办法
    java实现图像的直方图均衡以及灰度线性变化,灰度拉伸
    java关于邮件发送
    我都博客第一天
    开博随笔
    git使用
  • 原文地址:https://www.cnblogs.com/lailailai/p/4873177.html
Copyright © 2020-2023  润新知