Created
November 14, 2022 21:46
-
-
Save rohanjai777/6fe87f0af7b0cd570d53c4cc96f2d885 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int solve(int A, int[][] B) { | |
ArrayList<Integer>[] graph = new ArrayList[A+1]; //A+1 because vertex are from 1 to A | |
for(int i=0;i<=A;i++){ //make graph | |
graph[i] = new ArrayList<>(); | |
} | |
for(int i=0;i<B.length;i++){ | |
int v1 = B[i][0]; | |
int v2 = B[i][1]; | |
graph[v1].add(v2); | |
} | |
boolean visited[] = new boolean[A+1]; | |
boolean ans = dfs(graph,1,A,visited); //apply dfs | |
return ans ? 1 : 0; | |
} | |
public boolean dfs(ArrayList<Integer>[] graph, int src, int target, boolean visited[]){ //apply simple dfs to check if equal | |
if(src == target) return true; | |
visited[src] = true; | |
for(Integer nbr : graph[src]){ | |
if(visited[nbr] == false){ | |
boolean ans = dfs(graph,nbr,target,visited); | |
if(ans) return true; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment