GraphCode
GraphCode
*;
public class D2_graphBasics {
int u = sc.nextInt();
int v = sc.nextInt();
int wt = sc.nextInt();
visited[src] = true;
ArrayList<Edge> l = graph[src];
for(Edge e : l){
if(visited[e.nbr]==false){
boolean a = hasPath(e.nbr,dest,graph,visited);
if(a) return true;
}
return false;
}
}
}
-----------------------------------------------------------------------------------
-------
Leetcode 1971
Find if Path Exist in graph
Solution :
class Solution {
public boolean validPath(int n, int[][] edges, int src, int dest) {
List<Integer>[] graph = new ArrayList[n];
for(int i=0; i<n; i++){
graph[i] = new ArrayList<>();
}
graph[u].add(v);
graph[v].add(u);
}
public boolean hasPath(List<Integer>[] graph, int src, int dest, boolean[] visited)
{
if(src==dest){
return true;
}
visited[src] = true;
List<Integer> l = graph[src];
for(Integer e : l){
if(visited[e]==false){
boolean a = hasPath(graph,e,dest,visited);
if(a) return true;
}
}
return false;
}
-----------------------------------------------------------------------------------
---
input :
7
8
0 1 10
1 2 10
2 3 10
0 3 40
3 4 5
4 5 3
5 6 3
4 6 8