An algorithm for searching all paths between two points based on a graph's contiguity list implementation

Keywords: network

The algorithm is implemented in C++.

Why write this algorithm? Because it is so hard to find only the implementation of the adjacency matrix on the network, I have made an implementation of the adjacency chain table myself, which can increase the speed.

This is achieved by using one of three stacks to traverse all vertices, the second stack to record the parent nodes of the first stack, and the third stack to record one of the paths being traversed

The reason you need three paths is that each time you add a node to the third stack, you need to determine that the third top element of the stack is the parent node that added the element.

An array is also needed to record whether the node has been visited


template <class T>
bool Picture<T>::findway()
{
    cout<<"Input:";
    T first,second;
    cin>>first>>second;
    cout<<"Output:"<<endl;
    int n0,n1;
    n0=getVerticePos(first);
    n1=getVerticePos(second);
    if(n0==-1||n1==-1)  //Node that does not exist
        return false;
    bool *judge=new bool[numVertices];  //Determine whether a node has traveled
    for(int i=0;i<numVertices;i++)
        judge[i]=false;
    Edge *loc;
    stack <int> s;  //Traversing through nodes
    stack <int> parent; //Record the previous node
    stack <int> q;  //Record one of them
    s.push(n0);
    parent.push(-1);
    int i,j,length;
    int path[50];
    while(!s.empty())
    {
        i=s.top();
        s.pop();
        j=parent.top();
        parent.pop();
        judge[i]=true;
        if(q.empty())
            q.push(i);
        else
        {
            while(q.top()!=j)
            {
                judge[q.top()]=false;
                q.pop();
            }
            q.push(i);
        }
        if(i==n1)   //Find the end point
        {
            length=0;
            while(!q.empty())
            {
                path[length++]=q.top();
                q.pop();
            }
            for(int i=length;i>0;i--)
            {
                cout<<NodeTable[path[i-1]].data;
                q.push(path[i-1]);
            }
            cout<<endl;
            continue;   //No longer add adjacent nodes to stacks
        }

        loc=NodeTable[i].adj;
        while(loc!=NULL)
        {
            if(judge[loc->dest]==false) //Node This path has not been visited
            {
                s.push(loc->dest);
                parent.push(i);
            }
            loc=loc->link;
        }
    }
    return true;
}
template <class T>
int Picture<T>::getVerticePos(const T vertex)
{
    for(int i=0;i<numVertices;i++)
        if(NodeTable[i].data==vertex)
            return i;   //Find Return Subscript
    cout<<vertex<<endl;
    return -1;  //Return-1 not found
}

The graph is built without writing

Test data as shown in Fig.


Posted by onicsoft on Thu, 02 Jul 2020 08:19:55 -0700