c++ - 我正在尝试使用 STL 堆栈执行 DFS,但它给出了意想不到的结果
问题描述
这是我的 DFS 代码,它应该提供如下输出:
以下是深度优先遍历:0 1 3 2 4
但它给出了输出:
以下是深度优先遍历:0 2 3 4 1 1 1
我没有再次访问访问过的元素,但它仍然无法正常工作。
#include<bits/stdc++.h>
using namespace std;
void addEdge(vector<int> adj[], int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void DFS(vector<int> adj[], int V, int s)
{
stack<int> st;
bool visited[V];
for(int i=0; i<V;i++)
visited[i] = false;
visited[s] = true;
st.push(s);
while(st.empty()==false)
{
int n=st.top();
st.pop();
visited[n] =true;
cout<<n<<" ";
for(int v:adj[n])
{
if(visited[v]==false)
st.push(v);
}
}
}
int main()
{
int V=5;
vector<int> adj[V];
addEdge(adj,0,1);
addEdge(adj,0,2);
addEdge(adj,2,3);
addEdge(adj,1,3);
addEdge(adj,1,4);
addEdge(adj,3,4);
cout << "Following is Depth First Traversal: "<< endl;
DFS(adj,V,0);
return 0;
}
解决方案
除非有充分的理由使用显式堆栈,否则我建议使用递归(隐式堆栈)。但是,我将修复它,对您的代码进行最少的更改。
有 3 件事要解决,我在下面留下了评论。
void DFS(vector<int> adj[], int V, int s)
{
stack<int> st;
vector<bool> visited(V, false); // 1. Don't use VLA as it is not standard
// 2. Remove redundant first element visit marking
st.push(s);
while(st.empty()==false)
{
int n=st.top();
st.pop();
// 2. Check if visited since some elements may have added multiple times
// (Some are pushed in the stack many times but not never visited yet)
if (visited[n])
continue;
visited[n] =true;
cout<<n<<" ";
// 3. Reverse the order of iteration
for(auto v = adj[n].rbegin(); v != adj[n].rend(); ++v)
{
if(visited[*v]==false)
st.push(*v);
}
}
}
添加更多关于否的信息。3 - 实际上0 2 3 4 1
也是一个有效的 DFS 订单。但adj[n]
由于 Stack 的性质,它从相反的顺序遍历。所以反向迭代会使迭代结果为0 1 3 2 4
。
推荐阅读
- asynchronous - 如何转换未来的输出?
- angular-material - 在文件夹结构的内部级别使用 mat-icon 模块时出现问题
- yocto - 在 Yocto 中更新 wl18xx 驱动程序
- sql - jOOQ:DDLDatabase 生成器中是否存在可延迟约束的限制?
- python - 熊猫根据列值重复行
- java - Java Spring Hibernate Schema-Validation:缺少表
- java - 如何扫描特定目录以查找具有特定扩展名的文件?
- php - 显示短日而不是长日 PHP
- r - Dplyr group_by summarise 保留组内每列的最小值/最大值,具体取决于列后缀
- git - 用于持续集成和交付的 Azure DevOps Git 粒度触发器构建