Friday, March 11, 2022

Leet Code - 1971 : Find if Path Exists in Graph

 Example 1:

Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Output: true
Explanation: There are two paths from vertex 0 to vertex 2:
- 0 → 1 → 2
- 0 → 2


package pep.Day38;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Has_Path_LeetCode_1971 {

public static void main(String[] args) throws Exception {
int[][] edges = {{0, 1}, {1, 2}, {2, 0}};
System.out.println(validPath(3, edges, 0, 2));
}

public static boolean validPath(int n, int[][] edges, int source, int destination) {

ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}

for (int i = 0; i < edges.length; i++) {
int src = edges[i][0];
int dest = edges[i][1];
graph.get(src).add(dest);
graph.get(dest).add(src);
}
boolean[] visited = new boolean[n];
boolean res = check(graph, source, destination, visited);

return res;
}

private static boolean check(ArrayList<ArrayList<Integer>> graph, int source, int destination, boolean[] visited) {
if (source == destination)
return true;

// if (visited[source] != true) {
// visited[source] = true;
// for (int nbr : graph.get(source)) {
// boolean res = check(graph, nbr, destination, visited);
// if (res)
// return true;
// }
// }

visited[source] = true;
for (int nbr: graph.get(source)){
if (!visited[nbr]){
boolean res = check(graph, nbr, destination, visited);
if (res)
return true;
}
}


return false;
}

}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...