Check if given undirected graph is connected or not

Objective: Given an undirected graph, write an algorithm to find out whether the graph is connected or not.

Graph Connectivity: If each vertex of a graph is connected to one or multiple vertices then the graph is called a Connected graph whereas if there exists even one vertex which is not connected to any vertex of the graph then it is called Disconnect or not connected graph.

Approach: Use Depth-First Search (DFS)

Create a boolean visited [] array. Start DFS from any vertex and mark the visited vertices in the visited[] array. Once DFS is completed check the iterate the visited [] and count all the true’s. If this count is equal to no of vertices means all vertices are traveled during DFS implies graph is connected if the count is not equal to no of vertices implies all the vertices are not traveled means graph is not connected or disconnected.

public class Solution
{ 
    public static void runDFS(int[][] edges,int sv,boolean[] visited)
    {
        visited[sv]=true;
        int n=edges.length;
        for(int i=0;i<n;i++)
        {
            if(edges[sv][i]==1 && !visited[i])
            {
                runDFS(edges,i,visited);
            }
        }
    }
    public static boolean isConnected(int[][] edges,int sv)
    {
        boolean[] visited=new boolean[edges.length];
        runDFS(edges,sv,visited);
        for(int i=0;i<edges.length;i++)
        {
            if(visited[i]==false)
                return false;
        }
        return true;
    }
	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];
        int fv=0;
        for(int i=0;i<E;i++)
        {
            fv=s.nextInt();
            int sv=s.nextInt();
            edges[fv][sv]=1;
            edges[sv][fv]=1;
        }
        System.out.println(isConnected(edges,fv));
	}
}

Last updated