在深度搜索的暗示中似乎有什么问题?
#include <bits/stdc++.h>
using namespace std;
struct Graph
{
int V;
vector<list<int>> network;
Graph(int V);
void addEdge(int s, int v);
void performDFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
network.resize(V);
}
void Graph::addEdge(int s, int v)
{
network[s].push_back(v);
}
void Graph::performDFS(int s)
{
vector<bool>visited;
visited.resize(V, false);
visited[s] = true;
list<int> Stack;
Stack.push_back(s);
cout<<s<<" ";
while(!Stack.empty())
{
int abc = Stack.back();
for(int adjacent:network[abc])
{
if(!visited[adjacent])
{
visited[adjacent] = true;
cout<<adjacent<<" ";
Stack.push_back(adjacent);
abc = adjacent;
}
}
Stack.pop_back();
}
}
int main()
{
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.performDFS(1);
}
输出应为2 0 1 3,同时给出2 0 3 1。
- 遍历开始于2,标记为真实并打印。
- 然后分配了相邻的0,该0被标记为探索,打印并将其推到堆栈上。 ABC已更改为0。
- 在此之后,相邻应分配1,因为它是唯一未探索的边缘,但由于某种原因而不是。
需要帮助...
#include <bits/stdc++.h>
using namespace std;
struct Graph
{
int V;
vector<list<int>> network;
Graph(int V);
void addEdge(int s, int v);
void performDFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
network.resize(V);
}
void Graph::addEdge(int s, int v)
{
network[s].push_back(v);
}
void Graph::performDFS(int s)
{
vector<bool>visited;
visited.resize(V, false);
visited[s] = true;
list<int> Stack;
Stack.push_back(s);
cout<<s<<" ";
while(!Stack.empty())
{
int abc = Stack.back();
for(int adjacent:network[abc])
{
if(!visited[adjacent])
{
visited[adjacent] = true;
cout<<adjacent<<" ";
Stack.push_back(adjacent);
abc = adjacent;
}
}
Stack.pop_back();
}
}
int main()
{
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.performDFS(1);
}
The output should be 2 0 1 3, while this is giving 2 0 3 1.
- The traversal starts at 2, which is marked true and printed.
- Then adjacent is assigned 0, which is marked as explored, printed and pushed onto the stack. abc is changed to adjacent which is 0.
- After this, adjacent should get assigned 1, since it is the only unexplored edge around 0, but for some reason, it doesn't.
Need help with this...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在访问该顶点(从堆栈中弹出),而不是将其添加到堆栈时:
输出:输出:
在线gdb 在这里
You need to print the vertex when it is visited (popped from the stack) rather than when you add it to the stack:
Outputs:
Online GDB here