[英]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++.我正在使用 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 0->1,4,3
1->2 1->2
2->3 2->3
3-> 3->
4->2 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) : find_paths(0,3) :
0->1->2->3 0->1->2->3
0->4>2>3 0->4>2>3
0->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.要获得所有解决方案,而不仅仅是最短的解决方案,您可以保留一份在遍历过程中导致成功的所有路径的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.