-1

I want to find all the connected components in a graph. which is different from Solution For example my graph is as follows:

enter image description here

I want to find the connected component with the minimum cost. I am trying to use DFS to find the connected component and then add those component cost which covers all the vertices in an array find minimum of them and return it. But when I use DFS I always get the "path" instead of "connected component" that covers all the vertices. Example: enter image description here

Component with edges A-B,A-C,A-E,B-E having sum 10 is not coming as the output for my code as it is giving the paths. Below is my recursive code.

public void dfs(int node,int[][] visited,int[] v,int p){
    //System.out.println("DFS call on node "+node+" with pathsum "+p);
    //DFS call on Node "node" so making this node visited
    v[node]=1;
    //Checking whether the all the nodes in the graph are vsited.
    //if yes add this path sum to array.
    if(wp(v)){
        System.out.println("Adding path sum "+p);
        res.add(p);
        return;
    }
    for(int i=0;i<n;i++){
    //calling dfs on all the non visited nodes which have a path to them from node "node"
        if(v[i]==0 && visited[node][i]!=0){
            int[] cl=v.clone();
            //p=p+visited[node][i];
            dfs(i,visited,cl,p+visited[node][i]);
        }
    }
    return;
}

Can anyone help me out for this.

sForSujit
  • 987
  • 1
  • 10
  • 24
Abhishek Gangwar
  • 1,697
  • 3
  • 17
  • 29
  • Are ya solving the ***Matrix Attack Challenge***? – Yahya Jul 13 '17 at 08:32
  • Are you sure you are looking for connected components? Take a look at the [definition of connected components](https://en.wikipedia.org/wiki/Connected_component_(graph_theory)). I think you are missing something or that the question is not clear enough. – A. Sarid Jul 13 '17 at 08:38
  • The graphs you gave are connected components as a whole. Maybe you're looking for some sub-graph. Please try to define this better. – A. Sarid Jul 13 '17 at 08:39
  • 1
    Is it possible you are looking for the [Minimum Spanning Tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree)? – Sentry Jul 13 '17 at 08:49

1 Answers1

1

connected component has nothing with cost. DFS helps you to find connected components. You can mark vertices with 1 for first component, 2 for second and so on.

I think you use wrong term when you say connected component with minimal cost. Maybe you mean minimum spanning tree. If you really want to find connected component with minimal cost(but your images have only 1 component) you can mark all vertices with numbers and then calculate sum of all edges that connect those vertices.

If you want to find minimum spanning tree in graph you can use Prim's algorithm or Kruskal's algorithm. Both of them are pretty simple