简体   繁体   中英

Graph - Adjacency List C++ - All Paths from source to destination

I am trying to find all paths from a source node to a destination node in a graph. The graph is directed. I am using a rather simple adjacency list representation for the graph with C++. This is what I use for the nodes:

struct node
    {
        int id;
        std::vector <int> neighbours;
    };

Neighbours are the nodes that you can reach from a node.

This is what I use to store the whole graph:

std::vector < node > graph;

Example:

在此处输入图片说明

For the graph above, using the code:

for(int i=0;i<graph.size();i++)
    {
        std::cout<<graph[i].id<<"->";
        for(int j=0;j<graph[i].neighbours.size();j++)
        {
            std::cout<<graph[i].neighbours[j].id;
            if(j!=graph[i].neighbours.size()-1)
                std::cout<<",";
        }
        std::cout<<std::endl;
    }

Gives me all the adjacencies correctly as:

0->1,4,3

1->2

2->3

3->

4->2

Now, I want to write such a function:

void find_paths(int start, int end)

That when you give the start and ending points, it will print out all possible paths from the start to the end point.

Example: When I run,

find_paths(0,3) :

0->1->2->3

0->4>2>3

0->3

I want such an output. Performance is not really an issue here. Any working algorithm could do. What sort of algorithm can I use to solve such a problem? Also, if there are no possible paths, how can I get the function to recognize this?

Have a look at Breadth first search and Depth first search . Both methods are designed to traverse the graph, in different orders, to find a certain node.

To get all solutions and not just the shortest one, you could keep a list of all paths which led to success during traversal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM