0% found this document useful (0 votes)
3 views

Import Java

The Java program defines a class that counts the number of connected components in an undirected graph. It uses depth-first search (DFS) to explore the graph, represented as an adjacency list, and tracks visited nodes. The main method demonstrates the functionality with a sample graph, outputting the number of components found.

Uploaded by

vicemkr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Import Java

The Java program defines a class that counts the number of connected components in an undirected graph. It uses depth-first search (DFS) to explore the graph, represented as an adjacency list, and tracks visited nodes. The main method demonstrates the functionality with a sample graph, outputting the number of components found.

Uploaded by

vicemkr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

*;

public class Main {

public int countComponents(int n, int[][] edges) {

List<List<Integer>> adjList=new ArrayList<>();

for(int i=0;i<n;i++)

adjList.add(new ArrayList<>());

for(int[] edge:edges)

adjList.get(edge[0]).add(edge[1]);

adjList.get(edge[1]).add(edge[0]);

int components=0;

boolean[] visited=new boolean[n];

for(int i=0;i<n;i++)

if(!visited[i])

dfs(i,adjList,visited);

components++;

return components;

public void dfs(int node,List<List<Integer>> adjList,boolean[] visited)

visited[node]=true;

for(int neighbor:adjList.get(node))

{
if(!visited[neighbor])

dfs(neighbor,adjList,visited);

public static void main(String[] args) {

Main solution = new Main();

int n = 6;

int[][] edges = {{0, 1}, {2, 3}, {4, 5}};

System.out.println(solution.countComponents(n, edges)); // Output: 2

You might also like