Depth first traversal and breadth first traversal of Graphs

Keywords: Programming Python

;

In recent days, the examination of reviewing data structure is also a process of checking the defects and making up the omissions, so write down the handwritten code. In addition, the problem that it's better not to duplicate the name of the actual participating parameter in c/c + + class has puzzled and drunk for a long time

The function pointer void (*visit) can receive a function name and take the function as a parameter, similar to the function programming in python
The return value of the pointer function int *visit is an address value. The return value of a function must be accepted by a pointer variable of the same type, that is to say, a pointer function must have a return value of a function, and in a calling function, the return value of a function must be assigned to a pointer variable of the same type.

Note that in c/c + +, a member function and a member parameter cannot have the same name,

class A
{
private:
    int a;
public:
    A(int a){a=a;}  //This method is not available. The scope of parameter a will override the scope of member variable, so member variable a will not be assigned
}

Next are two traversal methods of Graphs
The first is DFS (depth first traversal), which recursively accesses the nearest neighbor vertex from a vertex until the end returns to the vertex with other neighbors for recursion

template<class T>
void AdjListUndirGraph<T>::DFS(int v,void (*(visit)(const T &e)))const
{
    SetTag(v,true);
    T e;
    GetElem(v,e);
    (*visit)(e);
    for(int w=FirstAdjVex(v);w>=0;w=NextAdjVex(v,w))
        if(!GetTag(w))
            DFS(w);
}
template<class T>
void AdjListUndirGraph<T>::DFSTraverse(void (*(visit)(const T &e)))const
{
    int v;
    for(v=0;v<GetVexNum();v++)
        SetTag(v,false);
    for(v=0;v<GetVexNum();v++)
        if(!GetTag(v))
            DFS(v,visit);
}

The second is BFS (breadth first traversal). All adjacent vertices of a vertex are queued and visited, then queued in turn, and then the adjacent vertices of the adjacent vertices are queued, then queued in turn, and repeated until the end of the visit

template<class T>
void AdjListDirGraph<T>::BFS(int v,void (*visit)(const T &e))const
{
    SetTag(v,true);
    T e;
    GetElem(v,e);
    (*visit)(e);
    LinkQueue q;
    q.InQueue(v);
    while(!q.Empty())
    {
        int u,w;
        q.OutQueue(u);
        for(w=FirstAdjVex(u);w>=0;w=NextAdjVex(u,w))
            if(!GetTag(w))
            {
                SetTag(w,true);
                GetElem(w,e);
                (*visit)(e);
                q.InQueue(w);
            }
}
template<class T>
void AdjListDirGraph<T>::BFSTraverse(void (*visit)(const T &e))const
{
    int v;
    for(v=0;v<GetVexNum;v++)
        SetTag(v,false);
    for(v=0;v<GetVexNum;v++)
        if(!GetTag(v))
            BFS(v,visit);
}

Posted by Fakcon on Mon, 04 May 2020 03:05:09 -0700