查找从给定起始节点到结束节点的所有可能路径

时间:2019-01-06 06:52:58

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

我正在尝试在使用邻接表的图形中打印从源到目标的所有路径,并对其进行加权和定向。我正在尝试在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

此图:Graph1

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

此图:Graph2

  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

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

2 个答案:

答案 0 :(得分:0)

这个想法可能会有所帮助

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

答案 1 :(得分:0)

乙型肝炎尚不清楚。如果它表示路径的末端节点,则路径可能存在或可能不存在于有向图中,并且可能会失败。一种方法是一次从一个节点开始遍历图,访问的每个节点都会有排队的节点给出其路径。如果有n个节点,则将遍历n次图,并且将使队列变空n次。

相关问题