问题描述
我正在做图形的 DFS 遍历。 这是我的代码:
//Function to return a list containing the DFS traversal of the graph.
vector<int>dfsOfGraph(int V,vector<int> adj[])
{
vector<int> res;//value to return
bool to_visit[V];
for(int i=0;i<V;i++){//making all nodes to be visited
to_visit[i]=true;
}
stack<int> stack1,stack2;//stack 2 is additional stack to reverse order of nodes
stack1.push(0);
to_visit[0]=false;
while(!(stack1.empty())){
int x=stack1.top();
res.push_back(x);
stack1.pop();
for(auto iter:adj[x]){
if(to_visit[iter]){
stack2.push(iter);
to_visit[iter]=false;
}
while(!stack2.empty()){
x=stack2.top();
stack1.push(x);
stack2.pop();
}
}
}
return res;
}
即使在我使用额外的堆栈来反转顺序之后,此代码仍会以数字的相反顺序打印节点。 我无法弄清楚为什么它仍然以相反的顺序打印节点。 这是完整的代码 link
解决方法
使用第二个堆栈来反转访问节点的顺序是对内存和时间的低效使用,即使它被正确实现。
移除第二个堆栈。
当您在向量 ( res ) 中访问节点时,您可以在从函数返回之前使用 STL algorithm function reverse 简单地反转顺序。
std::reverse( res.begin(),res.end() );