简体   繁体   中英

Finding the number of connected components in an undirected graph

Source:

here

Problem:

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.

Approach:

class Solution 
{
public:
    int countComponents(int n, vector<vector<int>>& edges) 
    {
        std::vector<bool> v(n, false);
        int count = 0;

        for(int i = 0; i < n; ++i)
        {
            if(!v[i])
            {
                dfs(edges, v, i);
                count++;
            }
        }
        return count;
    }

    void dfs(std::vector<std::vector<int>>& edges, std::vector<bool>& v, int i)
    {
        if(v[i] || i > edges.size())
            return;

        v[i] = true;
        for(int j = 0; j < edges[i].size(); ++j)
            dfs(edges, v, edges[i][j]);
    }
};

Error:

heap-buffer overflow

I am not understanding why my code is causing a heap-buffer overflow for the test case:

5
[[0,1],[1,2],[2,3],[3,4]]

Any suggestions on how to fix my code would be really appreciated.

My guess is that your edges vector has only four elements in it for the provided input, since there is no outgoing edge from vertex 4. Your dfs function then eventually recurs into the point where i == 4, but your edges vector has only 4 elements, thus the last valid possition is edges[3] .

I suggest that you represent a vertex with no outgoing vertices with an empty vector.

Also, the second part of the if statement

if(v[i] || i > edges.size())
        return;

seems unecceserry and should probably just be

if(v[i])
        return;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM