> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/graphs-bfs-and-dfs/connected-components-in-an-undirected-graph.md).

# Connected Components in an undirected graph

Given an undirected graph, print all connected components line by line. For example consider the following graph.

[![SCCUndirected](https://media.geeksforgeeks.org/wp-content/cdn-uploads/gq/2015/06/SCCUndirected.png)](https://media.geeksforgeeks.org/wp-content/cdn-uploads/gq/2015/06/SCCUndirected.png)

Finding connected components for an undirected graph is an easier task. We simple need to do either BFS or DFS starting from every unvisited vertex, and we get all strongly connected components. Below are steps based on DFS.

```
1) Initialize all vertices as not visited.
2) Do following for every vertex 'v'.
       (a) If 'v' is not visited before, call DFSUtil(v)
       (b) Print new line character

DFSUtil(v)
1) Mark 'v' as visited.
2) Print 'v'
3) Do following for every adjacent 'u' of 'v'.
     If 'u' is not visited, then recursively call DFSUtil(u)
```

```java
public class solution {
    public static void runDFS(int[][] edges, int sv, boolean[] visited, ArrayList<Integer> smallAns) {
        visited[sv] = true;
        int n = edges.length;
        smallAns.add(sv);
        for (int i = 0; i < n; i++) {
            if (edges[sv][i] == 1 && !visited[i])
                runDFS(edges, i, visited, smallAns);
        }
    }

    public static ArrayList<ArrayList<Integer>> allConnected(int[][] edges) {
        boolean[] visited = new boolean[edges.length];
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        for (int i = 0; i < edges.length; i++) {
            if (!visited[i]) {
                ArrayList<Integer> smallAns = new ArrayList<>();
                runDFS(edges, i, visited, smallAns);
                Collections.sort(smallAns);
                ans.add(smallAns);
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int V = s.nextInt();
        int E = s.nextInt();
        int edges[][] = new int[V][V];
        for (int i = 0; i < E; i++) {
            int fv = s.nextInt();
            int sv = s.nextInt();
            edges[fv][sv] = 1;
            edges[sv][fv] = 1;
        }
        ArrayList<ArrayList<Integer>> ans = allConnected(edges);
        for (ArrayList<Integer> arr : ans)
            System.out.println(arr);
    }
}
```
