zoukankan      html  css  js  c++  java
  • 算法-图的路径查询-深度优先遍历

    #include <cassert>
    #include <vector>
    
    template<typename Graph>
    class Path
    {
    private:
        Graph &G;
        int s; //某一个点
        bool* visited;
        int* from;//路径
    
        void dfs(int v){
            visited[v] = true;
            typename Graph::adjIterator adj(G,v);
            for(int i =adj.begin();!adj.end();i= adj.next()){
                if(!visited[i]){
                    from[i] =v;
                    dfs(i);
                }
            }
        }
    public:
        Path(Graph &graph,int s):G(graph){
            //算法初始化
            assert(s>=0 && s < G.V());
            visited = new bool[G.V()];
            from = new int[G.V()];
            for(int i =0;i<G.V();i++){
                visited[i] = false;
                from[i] = -1;
            }
            this->s = s;
    
            //寻路算法
            dfs(s);
    
        };
        ~Path(){
            delete[] visited;
            delete[] from;
        }
        //从s到w是否有路径
        bool hasPath(int w){
            assert(w>=0 && w<G.V());
            return visited[w];
        }
    
        //从s到w路径是多少
        void path(int w,vector<int> &vec){
            stack<int> s;
            int p = w;
            while (p!=-1){
                s.push(p);
                p = from[p];
            }
            vec.clear();
            while (!s.empty()){
                vec.push_back(s.top());
                s.pop();
            }
            
            
        }
        //把路径打印出来
        void showPath(int w){
            vector<int> vec;
            path(w,vec);
            for(int i=0;i<vec.size();i++){
                cout<<vec[i];
                if(i==vec.size()-1)
                    cout<<endl;
                else
                    cout<<" --> ";
            }
    
        }
    
    };
  • 相关阅读:
    xp 安装 win7 64
    局域网内传输文件速度慢
    安全和共享设置
    vs2005无法启动
    dos快速通道
    xp 共享 guest
    Java菜题
    Java序列化总结(最全)
    Bitset改进你的程序质量
    Java反射方法总结
  • 原文地址:https://www.cnblogs.com/Erick-L/p/12623248.html
Copyright © 2011-2022 走看看