我的BFS代码仅显示了从源到目标的直接路径,但没有显示所有可能的路径

时间:2018-08-12 10:31:14

标签: c path graph-theory breadth-first-search

我想从给定的源和目标打印所有可能的路径。但是在我的BFS代码中,它仅显示两条路径,而不显示多条路径。对于给定图,其中n = 4,边= 6,给定,

1-2
1-3
1-5
5-3
5-4
3-4
3-2

它应该已经打印了3条路径:

1-5-4
1-3-4
1-5-3-4

但是它只显示了这两个路径

1-3-4
1-5-4

这是我的示例代码,用于查找到目标路径的src

#include <stdio.h>

int queue1[100], state[100], parent[100];
int front = 0, rear = -1, maxSize = 100;
int count = 0;
int initial = 1, waiting = 2, visited = 3;
int n, e;
int adj[100][100];

bool isEmpty()
{
    return count == 0;

}
bool isFull()
{
    return count == maxSize;
}
void enqueue(int val)
{
    if (!isFull())
    {
        if (rear == maxSize - 1)
        {
            rear = -1;
        }
        rear++;
        queue1[rear] = val;
        count++;
    }
}
int dequeue()
{
    int val = queue1[front];
    front++;

    if (front == maxSize)
    {
        front = 0;
    }
    count--;
    return val;
}
void BFS_Traversal(int src, int des)
{
    int done = 0;
    enqueue(src);
    state[src] = waiting;
    parent[src] = -1;

    printf("path ");

    while (!isEmpty() && done == 0)
    {

        src = dequeue();
        // printf("%d ",src);
        state[src] = visited;

        for (int i = 1; i <= n; i++)
        {

            if (adj[src][i] == 1 && state[i] == initial)
            {
                enqueue(i);
                state[i] = waiting;
                parent[i] = src;
                if (i == des)
                {
                    state[i] = initial;
                    int k = des;

                    do
                    {
                        printf("%d ", k);
                        k = parent[k];
                    } while (k != -1);
                    printf("\n");
                }
            }
        }
    }

}
int main()
{
    int src, start, end, des;
    scanf("%d%d", &n, &e);

    for (int i = 1; i <= e; i++)
    {
        scanf("%d%d", &start, &end);
        adj[start][end] = 1;
    }

    for (int i = 1; i <= n; i++)
    {
        state[i] = initial;
    }
    for (int k = 1; k <= n; k++)
    {
        parent[k] = -1;
    }

    scanf("%d%d", &src, &des);
    BFS_Traversal(src, des);
}

因此,您可以看到未显示1-5-3-4路径,因为它们已被访问。我应该如何修改此代码以打印所有可能的路径?

0 个答案:

没有答案