- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Java Program to Check Whether Undirected Graph is Connected Using DFS

## Introduction

This Java program checks whether an undirected graph is connected or not using DFS. It takes input from the user in the form of the number of vertices and edges in the graph, and the edges themselves. It creates an adjacency list to store the edges of the graph, and then uses DFS to traverse the graph and check if all vertices are visited.

If all vertices are visited, then the graph is connected. The time complexity of this program is O(V+E), where V is the number of vertices and E is the number of edges in the graph, and the space complexity is O(V+E) due to the adjacency list.

## Definition

An undirected connected graph is a graph in which all vertices are connected to each other via edges. In such a graph, there exists a path between any two vertices. If we start from any vertex and traverse through the edges, we can reach all other vertices in the graph. This concept is important in graph theory and has many applications, including network analysis and geographical maps. Determining the connectivity of an undirected graph is a fundamental problem in graph theory, and various algorithms exist to solve it. One of the popular algorithms is DFS, which can be used to determine if an undirected graph is connected or not.

### Approach

Define a function dfsTraversal that performs DFS traversal on the given graph, starting from a given vertex. This function takes three parameters −

graph − the adjacency list of the graph

vertex − the vertex from which DFS traversal should start

visited − an array of boolean values indicating whether a vertex has been visited or not

The dfsTraversal function marks the given vertex as visited, and then recursively visits all its unvisited neighbors.

Define a function isConnected, which checks whether the given graph is connected or not. This function takes two parameters −

graph − the adjacency list of the graph

vertices − the number of vertices in the graph

The isConnected function initializes an array of boolean values called visited to keep track of visited vertices. It then performs DFS traversal from the first vertex of the graph using the dfsTraversal function. Finally, it checks if all the vertices have been visited or not. If all the vertices have been visited, the graph is connected, and the function returns true. Otherwise, it returns false.

In the main function −

Read the number of vertices and edges in the graph.

Initialize the adjacency list graph.

Read the edges of the graph and add them to the adjacency list.

Call the isConnected function to check whether the graph is connected or not, and print the result accordingly.

The key idea behind this approach is to use DFS to visit all the vertices in the graph and mark them as visited. If all the vertices have been visited, then the graph is connected. If not, then there must be some vertices that are not connected to the rest of the graph, which means the graph is not connected.

## Example 1

Here's a Java program to check whether an undirected graph is connected or not using Depth-First Search (DFS) −

import java.util.*; public class ConnectedGraphDFS { // function to perform DFS traversal on the graph private static void dfsTraversal(ArrayList<Integer>[] graph, int vertex, boolean[] visited) { visited[vertex] = true; // visit all the neighbors of the vertex for(int neighbor : graph[vertex]) { if(!visited[neighbor]) { dfsTraversal(graph, neighbor, visited); } } } // function to check whether the given graph is connected or not public static boolean isConnected(ArrayList<Integer>[] graph, int vertices) { boolean[] visited = new boolean[vertices]; // perform DFS traversal from the first vertex dfsTraversal(graph, 0, visited); // check if all the vertices are visited or not for(int i = 0; i < vertices; i++) { if(!visited[i]) { return false; } } return true; } // main function to test the program public static void main(String[] args) { Scanner sc = new Scanner(System.in); // read the number of vertices in the graph System.out.print("Enter the number of vertices in the graph: "); int vertices = sc.nextInt(); // read the number of edges in the graph System.out.print("Enter the number of edges in the graph: "); int edges = sc.nextInt(); // initialize the adjacency list ArrayList<Integer>[] graph = new ArrayList[vertices]; for(int i = 0; i < vertices; i++) { graph[i] = new ArrayList<Integer>(); } System.out.println("Enter the edges of the graph:"); // read the edges of the graph for(int i = 0; i < edges; i++) { int u = sc.nextInt(); int v = sc.nextInt(); // add edge between u and v graph[u].add(v); graph[v].add(u); } // check whether the graph is connected or not boolean isConnected = isConnected(graph, vertices); if(isConnected) { System.out.println("The graph is connected."); } else { System.out.println("The graph is not connected."); } } }

### Explanation

In this program, we first define a function dfsTraversal that performs DFS traversal on the given graph, starting from a given vertex. This function takes three parameters. The dfsTraversal function marks the given vertex as visited, and then recursively visits all its unvisited neighbors. Next, we define the function isConnected, which checks whether the given graph is connected or not. This function takes two parameters.

The isConnected function initializes an array of boolean values called visited to keep track of visited vertices. It then performs DFS traversal from the first vertex of the graph using the dfsTraversal function. Finally, it checks if all the vertices have been visited or not. If all the vertices have been visited, the graph is connected, and the function returns true. Otherwise, it returns false.

### Output

Enter the number of vertices in the graph: 6 Enter the number of edges in the graph: 5 Enter the edges of the graph: 0 1 1 2 2 3 4 5 5 4 Graph is not connected

## Example 2

Here's another Java program to check whether an undirected graph is connected or not using Depth-First Search (DFS) −

import java.util.ArrayList; import java.util.Scanner; public class GraphConnectivityDFS { private int V; private ArrayList<ArrayList<Integer>> adj; GraphConnectivityDFS(int v) { V = v; adj = new ArrayList<>(V); for (int i = 0; i < V; ++i) { adj.add(new ArrayList<>()); } } void addEdge(int v, int w) { adj.get(v).add(w); adj.get(w).add(v); } void dfsTraversal(int v, boolean[] visited) { visited[v] = true; for (int n : adj.get(v)) { if (!visited[n]) { dfsTraversal(n, visited); } } } boolean isConnected() { boolean[] visited = new boolean[V]; dfsTraversal(0, visited); for (int i = 0; i < V; ++i) { if (!visited[i]) { return false; } } return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of vertices in the graph: "); int V = scanner.nextInt(); System.out.print("Enter the number of edges in the graph: "); int E = scanner.nextInt(); GraphConnectivityDFS graph = new GraphConnectivityDFS(V); System.out.println("Enter the edges of the graph:"); for (int i = 0; i < E; i++) { int v = scanner.nextInt(); int w = scanner.nextInt(); graph.addEdge(v, w); } boolean connected = graph.isConnected(); if (connected) { System.out.println("Graph is connected"); } else { System.out.println("Graph is not connected"); } } }

### Output

Enter the number of vertices in the graph: 2 Enter the number of edges in the graph: 2 Enter the edges of the graph: 0 1 1 0 Graph is connected

## Conclusion

An undirected connected graph is a graph where all vertices are connected to each other, and there is a path between any two vertices.

Determining the connectivity of an undirected graph is an important problem in graph theory, and various algorithms exist to solve it, such as the DFS algorithm used in the Java program above.