> 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);
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mayanktyagi3111.gitbook.io/interview-prep/graphs-bfs-and-dfs/connected-components-in-an-undirected-graph.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
