在图表上执行BFS后,值不如预期

Value order not as expected, after performing a BFS on the graph?

本文关键字:执行 BFS      更新时间:2023-10-16

我正在尝试根据邻接列表创建图形。这是图的结构。

class Graph{
private:
    struct Vertex
    {
        int data;
        Vertex *next;
        set<int> anti;
    };
    struct Neighbors
    {
        Vertex *head;
    };
public:
    int Limit;
    list<int> print_list;
    Neighbors *adjacent;
    Graph(int Limit);
    Vertex* Add_Vertex(int data);
    void Connect(int before, int data);
    void Display();
    list<int> BFS(int v);
    list<int> DFS(int source);
};

代码完全很好地编译,但是当我尝试复制为链接或任何其他页面创建边缘的顺序时,我总是会得到不同的顺序。

我的问题是,是什么导致我的命令与他们的命令不同?我认为我正在顺利关注逻辑,但我没有产生2 0 3 1,而是产生2 3 0 1.我希望这些输出相似。


edges&amp;创建:

Graph::Vertex* Graph::Add_Vertex(int data)
{
    //Initialize vertex
    Vertex* temp = new Vertex;
    temp->data = data;
    temp->next = NULL;
    return temp;
}
void Graph::Connect(int first, int second)
{
    Vertex *temp;
    //Create a vertex and get pointer for second
    if (first != second) {
        //Create a vertex and get a pointer for first
        temp = Add_Vertex(first);
        //Connect created node to second vertex
        temp->next = adjacent[second].head;
        adjacent[second].head = temp;
    }
    temp = Add_Vertex(second); 
    //Connect created node to first vertex
    temp->next = adjacent[first].head; 
    adjacent[first].head = temp;

}

BFS实现(不包括主呼叫):

list<int> Graph::BFS(int from) {
    print_list.clear();
    bool *visited = new bool[Limit];
    for (int i = 0; i < Limit; i++)
        visited[i] = false;
    list<int> queue;
    visited[from] = true;
    queue.push_back(from);
    while (!queue.empty())
    {
        from = queue.front();
        print_list.push_back(from);
        queue.pop_front();
        Vertex *Displaying = adjacent[from].head;
        while (Displaying)
        {
            int adjacent_node = Displaying->data;
            if (!visited[adjacent_node])
            {
                visited[adjacent_node] = true;
                queue.push_back(adjacent_node);
            }
            Displaying = Displaying->next;
        }
    }
    return print_list;
}

另一个测试:

1 2,2 3,1 5,1 4,4 7,7 8,8 9,2 6,5 7

预期:

1 2 4 5 3 6 7 8 9

实际:

1 4 5 2 7 6 3 8 9

启动顶点为1。

BFS中,您使用队列跟踪您需要访问的节点。您从正面拉出下一个节点,然后添加新节点以访问到末尾。

您要使用的是堆栈 - 从末端添加和删除节点。这将围绕订单节点访问,并更改您生成的输出。

另外,您可以将代码放在BFS中不变,然后更改Connect以将新节点添加到邻居列表的 end ,而不是在开始时。