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;
    };    
  • 相关阅读:
    nyoj 42 一笔画 欧拉通路
    布丰投针实验1
    poj 1328 贪心
    uva 10026 贪心
    zoj 1375 贪心
    uva 103 经典DAG变形
    uva 11088 暴力枚举子集/状压dp
    jsp分页功能
    static静态变量的理解
    Vector & ArrayList 的主要区别
  • 原文地址:https://www.cnblogs.com/shuada/p/3468145.html
Copyright © 2011-2022 走看看