在图表上执行BFS后,值不如预期
Value order not as expected, after performing a BFS on the graph?
我正在尝试根据邻接列表创建图形。这是图的结构。
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 ,而不是在开始时。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 如何确认我的constexpr表达式实际上已经在编译时执行
- C++17中的并行执行策略
- QML按钮点击功能执行顺序
- 程序在执行程序的其余部分之前退出
- 为什么catch中的代码没有被执行
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 将执行、作业和WinAPI相乘
- 在 c++ 中执行 BFS 时出现分段错误
- 在图表上执行BFS后,值不如预期