我正在尝试在使用邻接表的图形中打印从源到目标的所有路径,并对其进行加权和定向。我正在尝试在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
我希望用户输入的两个值之间的所有路径。如果用户输入3和2
我希望输出是这样的:
3 -> 0 -> 2
3 -> 0 -> 1 -> 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)