• 算法-图的路径查询-广度优先遍历


    #include <cassert>
    #include <vector>
    
    template<typename Graph>
    class ShortestPath
    {
    private:
        Graph &G;
        int s; //某一个点
        bool* visited;
        int* from;//路径
        int *ord;//最短距离
    
    public:
        ShortestPath(Graph &graph,int s):G(graph){
            //算法初始化
            assert(s>=0 && s < G.V());
    
            visited = new bool[G.V()];
            from = new int[G.V()];
            ord = new int[G.V()];
    
            for(int i =0;i<G.V();i++){
                visited[i] = false;
                from[i] = -1;
                ord[i] = -1;
            }
            this->s = s;
    
            queue<int> q;
            //广度优先无向图最短路径算法
            q.push(s);
            visited[s] = true;
            ord[s]=0;
            while (!q.empty())
            {
                int v = q.front();
                q.pop();
                typename Graph::adjIterator adj(G,v);
                for(int i =adj.begin();!adj.end();i= adj.next()){
                    if(!visited[i]){
                        q.push(i);
                        visited[i] =true;
                        from[i]=v;
                        ord[i] = ord[v] +1
                    }
                }
            }
            
    
        };
        ~Path(){
            delete[] visited;
            delete[] from;
            delete[] ord;
        }
        //从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<<" --> ";
            }
    
        }
        int lenth(int w){
            assert(w>=0 && w<G.V());
            return ord[w];
        }
    
    };
  • 相关阅读:
    Python全栈开发之6、面向对象
    Python全栈开发之5、模块
    kvm恢复和删除快照
    virsh命令和虚拟机克隆
    Python全栈开发之4、迭代器、生成器、装饰器
    索引
    字段属性--唯一键
    安装虚拟机
    字段属性--自增长
    centos7安装kvm
  • 原文地址:https://www.cnblogs.com/Erick-L/p/12623336.html
Copyright © 2020-2023  润新知