|
| 1 | +import java.util.*; |
| 2 | +public class DisJointedMatrix { |
| 3 | + |
| 4 | + public static boolean isConnected(List<List<Integer>> graph , boolean visited[], int source, int destination) { |
| 5 | + if(source == destination) return true; |
| 6 | + if(visited[source]) return false;// loop prevention |
| 7 | + visited[source] = true; |
| 8 | + for(int neighbor: graph.get(source)){ |
| 9 | + if(!visited[neighbor]){ |
| 10 | + if(isConnected(graph,visited,neighbor,destination)){ |
| 11 | + return true; |
| 12 | + } |
| 13 | + } |
| 14 | + } |
| 15 | + return false; |
| 16 | + |
| 17 | + } |
| 18 | + public static void main(String[] args){ |
| 19 | + //Unidirectional Graph with Disjointed Components |
| 20 | + int vertex = 7; |
| 21 | + List<List<Integer>> adjacencyList = new ArrayList<>(); |
| 22 | + for(int i=0;i<vertex;i++){ |
| 23 | + adjacencyList.add(new ArrayList<>()); |
| 24 | + } |
| 25 | + adjacencyList.get(0).add(1); |
| 26 | + adjacencyList.get(1).add(2); |
| 27 | + adjacencyList.get(2).add(0); |
| 28 | + adjacencyList.get(3).add(4); |
| 29 | + adjacencyList.get(4).add(5); |
| 30 | + adjacencyList.get(5).add(3); |
| 31 | + //Component 1: 0-1-2 |
| 32 | + //Component 2: 3-4-5 |
| 33 | + //Component 3: 6 (Isolated Node) |
| 34 | + for(int i=0;i<vertex;i++){ |
| 35 | + System.out.print(i+": "); |
| 36 | + for(int neighbor:adjacencyList.get(i)){ |
| 37 | + System.out.print(neighbor+" "); |
| 38 | + } |
| 39 | + System.out.println(); |
| 40 | + } |
| 41 | + boolean visited[] = new boolean[vertex]; |
| 42 | + int source = 3; |
| 43 | + int destination = 5; |
| 44 | + if(isConnected(adjacencyList, visited, source, destination)){ |
| 45 | + System.out.println("There is a path from "+source+" to "+destination); |
| 46 | + }else{ |
| 47 | + System.out.println("There is no path from "+source+" to "+destination); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments