微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

DFS 遍历:节点以相反的顺序打印

如何解决DFS 遍历:节点以相反的顺序打印

我正在做图形的 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() );

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。