zoukankan      html  css  js  c++  java
  • 图的遍历

    1、深度优先遍历

    template<class T, class E>
    void DFS(Graph<T,E>& G, const T& v)
    {
        int i, loc, n=G.NumberOfVerticese();
        bool* visited = new bool[n];
        for(i=0;i<n;i++) visited[i] = false;
        loc = G.getVertexPos(v);
        DFS(G, loc, visited);
        delete []visited; 
    };
    
    template<class T, class E>
    void DFS(Graph<T,E>& G, int v, bool visited[])
    {
        cout<< G.getValue(v)<<" ";
        visited[v] = true;
        int w = G.getFirstNeighbor(v);
        while( w!= -1)
        {
            if(visited[w]==false) DFS(G, w, visited);
            w = G.getNextNeighor(v, w); //  顶点v排在w后的下一个邻接顶点
        }
    }

     2、广度优先遍历

    template<class T, class E>
    void BFS(Graph<T,E>& G, const T& v)
    {
        int i, w, n=G.NumberOfVertices();
        bool* visited = new bool[n];
        for(i=0;i<n;i++) visited[i]=false;
        int loc = G.getVertexPos(v);
        cout<<loc<<" ";
        visited[loc] = true;
        Queue<int> Q;
        Q.EnQueue(loc);
        while(!Q.IsEmpty()){
            Q.DeQueue(loc);
            w = G.getFirstNeighbor(loc);
            while(w!=-1)
            {
                 if(visited[w]==false){
                     cout<<G.getValue(w)<<" ";
                     visited[w]=true;
                     Q.EnQueue(w);
                 }
                 w = G.getNextNeighbor(loc, w);  // 顶点loc排在w后的下一个顶点
            }
        }
        delete[] visited;
    };    
  • 相关阅读:
    FileZilla 双向传输
    移动端弱网测试工具
    来源IP安全分析,对IP溯源
    推荐几款移动端抓包小工具
    一键清除Chrome
    resit阶段二
    redist集群
    redits04 快照配置
    ridts08管理工具
    redits07配置文件
  • 原文地址:https://www.cnblogs.com/shuada/p/3468145.html
Copyright © 2011-2022 走看看