-
Notifications
You must be signed in to change notification settings - Fork 117
/
Graphs:Is Connected ?
39 lines (38 loc) · 1.07 KB
/
Graphs:Is Connected ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.Scanner;
import java.util.*;
public class Solution {
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 sv=s.nextInt();
int ev=s.nextInt();
edges[sv][ev]=1;
edges[ev][sv]=1;
}
boolean ans=isConnected(edges);
System.out.println(ans);
}
public static boolean isConnected(int[][] edges){
boolean[] visited=new boolean[edges.length];
DFS(edges,0,visited);
for(boolean elem:visited)
{
if(elem==false)
return false;
}
return true;
}
public static void DFS(int[][] edges,int startver,boolean[] visited){
visited[startver]=true;
for(int i=0;i<edges.length;i++){
if(edges[startver][i]==1 && !visited[i]){
visited[i]=true;
DFS(edges,i,visited);
}
}
return ;
}
}