【问题标题】:Finding all possible paths from given start node to finish node查找从给定开始节点到结束节点的所有可能路径
【发布时间】:2023-04-01 00:35:01
【问题描述】:

我正在尝试在使用邻接列表的图中打印从源到目的地的所有路径。它是加权和定向的。我正在尝试在 BFS 中执行此操作。感谢您的帮助。我只有一条路。如何打印其他路径?

这是BFS函数:

void BFS(struct Graph *G,QUEUE *q)
{
    int j,i=0;
    while(!isEmpty(q))
    {
        int source = dequeue(q);
        printf("%d ",source);
        path[i]=source;
        i++;
        if(source==bitis)//source==end
        {
            for(j=0;j<i;j++)
                printf("%d ",path[j]);
        }
        struct node *head = G->adjList[source]->next;
        while(head)
        {
            if(G->adjList[head->source]->marked)
            {
                head = head->next;
                continue;
            }
            G->adjList[head->source]->marked = 1;
            enqueue(head->source,q);
            head = G->adjList[head->source]->next;
        }
    }
}

这是结构体:

struct node{
    int source;
    int w;
    int marked;
    struct node *next;
};
struct Graph{
    int V;
    int E;
    struct node **adjList;
};

这里是 adjList:

[0]->[2]->[1]
[1]->[2]
[2]->[3]->[1]
[3]->[0]
[4]->[3]->[2]

输出:4 3 0

此图:

  1. 5 个节点,9 个边(A=0,B=1,C=2,D=3,E=4)
  2. 开始节点:4 结束节点:0

这张图:

  1. 5个节点,8个边(A=0,B=1,C=2,D=3,E=4)
  2. 开始节点:4 结束节点:0

我想要用户输入的两个值之间的所有路径。如果用户输入 3 和 2

我希望输出是这样的:

3 -> 0 -> 2
3 -> 0 -> 1 -> 2

我希望我能表达我的问题。我的英语太差了。谢谢。

【问题讨论】:

  • 该图是加权和定向的。它是无环的吗?
  • 你好,我想没关系。因为根据给定的起点和终点,将找到所有路径。我编辑了我的问题。我放一张图。 @JimMischel
  • 是的,这很重要。如果您知道图中没有循环,则问题更容易解决。但是图表示例表明我们不能假设图表是非循环的。
  • 在您的示例图中,节点用字母标记,但您对第二个图说“开始节点 4,结束节点 0”。哪个节点(A、B、D、D、E)对应节点 4?我认为您需要解决您的问题。
  • 12

标签: c data-structures breadth-first-search


【解决方案1】:

这个想法可能会有所帮助

create a queue which will store path(s) of type vector
initialise the queue with first path starting from src

Now run a loop till queue is not empty
   get the frontmost path from queue
   check if the lastnode of this path is destination
       if true then print the path
   run a loop for all the vertices connected to the
   current vertex i.e. lastnode extracted from path
      if the vertex is not visited in current path
         a) create a new path from earlier path and 
             append this vertex
         b) insert this new path to queue

Print all paths from a given source to a destination using BFS

【讨论】:

    【解决方案2】:

    bitis 不清楚。如果它表示路径的结束节点,则路径可能存在也可能不存在于有向图中,并且可能会失败。一种方法是一次从一个节点开始遍历图,并且每个访问的节点都将有排队的节点给出其路径。如果有 n 个节点,图将被遍历 n 次,队列将变为空 n 次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多