首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >算法实现错误(DFS)

算法实现错误(DFS)
EN

Stack Overflow用户
提问于 2016-06-19 14:24:52
回答 2查看 212关注 0票数 0

我试图实现dfs,以便从启动节点打印路径。我遵循Coremen的算法,这是我的代码:DFS

代码语言:javascript
复制
#include<iostream>
#include<stack>
using namespace std;

int vertex,edge,source,time,adjacency_matrix[100][100],parent[100],Distance[100],Finishing_time[100];
string color[100];
stack<int> result;
void inputGraph();
void initialize();
void doDFS();
void doDFSvisit(int);
void printPath();
//void printAll();
//void printAdjacencyMatrix();
//void printColor();
//void printDistance();
//void printParent();

int main(void)
{
    inputGraph();
    //initialize();
    doDFS();
    printPath();
    //printAll();
    return 0;
}
void inputGraph()
{
    cout<<"Total vertex : ";
    cin>>vertex;
    cout<<"Total edge   : ";
    cin>>edge;
    int i,j;
    for(i=1; i<=edge; i++)
    {
        int start,finish;
        cout<<"Enter start and end node for edge "<<i<<" : ";
        cin>>start;
        cin>>finish;
        adjacency_matrix[start][finish]=1;
    }
    cout<<"The adjacency matrix is : "<<endl;
    for(i=1; i<=vertex; i++)
    {
        for(j=1; j<=vertex; j++)
        {
            cout<<adjacency_matrix[i][j]<<" ";
        }
        cout<<endl;
    }
}
void initialize()
{
    cout<<"Enter source node : ";
    cin>>source;
}
void doDFS()
{
    int i,j;
    for(i=1;i<=vertex;i++)
    {
        color[i]="white";
        parent[i]=0;
    }
    time=0;
    for(i=1;i<=vertex;i++)
    {
        if(color[i]=="white")
        {
            doDFSvisit(i);
        }
    }
}
void doDFSvisit(int node)
{
    int i;
    time=time+1;
    Distance[node]=time;
    color[node]="grey";
    for(i=1;i<=vertex;i++)
    {
        if(adjacency_matrix[node][i]==1)
        {
            if(color[i]=="white")
            {
                parent[i]=node;
                doDFSvisit(i);
           }
        }
    }
    color[node]="black";
    //extra line for result
    result.push(node);
    //
    time=time+1;
    Finishing_time[node]=time;
}
void printPath()
{
    cout<<"Path :"<<endl;
    int i;
    for(i=0;i<=result.size();i++)
    {
        cout<<result.top()<<" -> ";
        result.pop();
    }
    cout<<" End"<<endl;
}

我的问题是:

供投入:

6 6 1 2 1 4 2 3 3 4 5 3 5 6

我的产出应该是:

5 6 1 2 3 4完

但我的产出是:

5 6 1 2

从堆栈中打印值似乎会产生问题。请纠正我做错的地方,谢谢。

[ P.S.:用于输入的有向图的图片,http://imgur.com/fYsICiQ ]

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-06-19 21:21:18

print_path函数中有错误。您的for循环终止条件检查结果(堆栈)的大小,它通过pop调用减少每个循环迭代。

您的print_path函数应该如下所示:

代码语言:javascript
复制
void printPath(){
    cout<<"Path :"<<endl;
    int i;
    while(!result.empty()){
        cout << result.top() << " -> ";
        result.pop();
    }
    cout<<" End"<<endl;
}

此外,考虑一下这个外勤部的实现:

代码语言:javascript
复制
list<size_t> l[N];
bool used[N];
void DFS(size_t s){
    if (used[s])
        return;
    used[s] = true;
    for(auto i = l[s].begin(); i != l[s].end(); i++)
        if(!used[*i]){
            DFS(*i);
        }
}

使用的是全局bool数组,指示是否访问了I‘’th顶点。我们不需要给顶点着色。我们必须知道它是否已经访问过。

L是邻接列表(见http://www.geeksforgeeks.org/graph-and-its-representations/ )

我们在某个顶点上运行DFS。如果有人来访,我们什么也不做。否则,我们将此顶点标记为已访问。然后深入运行DFS,在每个顶点上运行相邻的当前顶点。

有关DFS的详细信息,请参阅搜索

票数 2
EN

Stack Overflow用户

发布于 2016-06-19 17:08:35

下面是如何在C++中实现DFS。首先是一些意见:

  • 我将使用邻接列表(std::vectors)而不是邻接矩阵。
  • Node不属于他们的邻居。假定它们是由父Graph对象拥有的。

因此,没有进一步的担心:

代码语言:javascript
复制
struct Node {
    std::vector<Node *> neighbors;
    // Other fields may go here.
}

void process(Node * node)
{
    // Actual logic for processing a single node.
}

// Of course, in idiomatic C++, this would be a template
// parameterized by a function object, rather than contain
// a hard-coded call to a fixed `process` function.
void depth_first(Node * start)
{
    std::stack        <Node *> pending = { start };
    std::unordered_set<Node *> visited;

    while (!pending.empty()) {
        Node * current = pending.pop();
        process(current);
        for (Node * neighbor : current->neighbors)
            if (visited.find(neighbor) == visited.end()) {
                pending.push  (neighbor);
                visited.insert(neighbor);
            }
    }
}

这个实现的一个好处是,为了获得BFS,您只需要用std::stack替换std::queue,其余的代码保持原样。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37908257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档