Search code examples
c++depth-first-search

Getting stackoverflow error while doing DFS on a graph


I am implementing a depth-first search on a graph to find the minimum sum of all connected components. But I'm getting a stack overflow error. I tried to debug it, but failed to do so.

Can anyone please help?

Here is the code:

#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, graph, cost,visited, c);
            ans += c;
        }
    }
    cout << ans << "\n";
}

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

Solution

  • Surely

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

    should be

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

    You really should have noticed that in the debugger.