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

在图形上执行DFS时出现stackoverflow错误

如何解决在图形上执行DFS时出现stackoverflow错误

我正在图形上实施深度优先搜索,以查找所有连接组件的最小和。但是我遇到了堆栈溢出错误。我试图调试它,但没有成功。

有人可以帮忙吗?

代码如下:

#include <bits/stdc++.h>

using namespace std;

void DFS(int x,vector<vector<int>> graph,vector<int> cost,vector<bool> visited,int &c)
{
    c = min(c,cost[x]);
    visited[x] = true;
    for (int n = 0; n < (int)graph[x].size(); n++)
    {
        if (!visited[graph[x][n]])
            DFS(x,graph,cost,visited,c);
    }
}

void solve()
{
    int nodes,edges;
    cin >> nodes >> edges;

    vector<int> cost(nodes);
    vector<bool> visited(nodes);
    vector<vector<int>> graph(nodes);

    for (int i = 0; i < nodes; i++)
        cin >> cost[i];

    for (int i = 0; i < edges; i++)
    {
        int a,b;
        cin >> a >> b;
        graph[a - 1].push_back(b - 1);
        graph[b - 1].push_back(a - 1);
    }
    int ans = 0;
    for (int i = 0; i < nodes; i++)
    {
        if (!visited[i])
        {
            int c = cost[i];
            DFS(i,c);
            ans += c;
        }
    }
    cout << ans << "\n";
}

int main()
{
    ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    solve();
}

解决方法

当然

DFS(x,graph,cost,visited,c);

应该是

DFS(graph[x][n],c);

您真的应该在调试器中注意到这一点。

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