首页 > 技术文章 > 图的遍历

shuada 2013-12-10 20:53 原文

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;
};    

 

推荐阅读