-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path*(Graph) HasPath (DFS)
66 lines (53 loc) · 1.72 KB
/
*(Graph) HasPath (DFS)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.io.*;
import java.util.*;
public class Main {
static class Edge {
int src;
int nbr;
int wt;
Edge(int src, int nbr, int wt){
this.src = src;
this.nbr = nbr;
this.wt = wt;
}
}
public static boolean hasPath(ArrayList<Edge>[] graph,int src,int dest,boolean[] visited){
if(src == dest){
return true;
}
visited[src] = true;
for(Edge e: graph[src]){
int ngbr = e.nbr;
if(visited[ngbr]==false){
boolean res = hasPath(graph,ngbr,dest,visited);
if(res){
return true;
}
}
}
return false;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vtces = Integer.parseInt(br.readLine());
ArrayList<Edge>[] graph = new ArrayList[vtces];
for(int i = 0; i < vtces; i++){
graph[i] = new ArrayList<>();
}
int edges = Integer.parseInt(br.readLine());
for(int i = 0; i < edges; i++){
String[] parts = br.readLine().split(" ");
int v1 = Integer.parseInt(parts[0]);
int v2 = Integer.parseInt(parts[1]);
int wt = Integer.parseInt(parts[2]);
graph[v1].add(new Edge(v1, v2, wt));
graph[v2].add(new Edge(v2, v1, wt));
}
int src = Integer.parseInt(br.readLine());
int dest = Integer.parseInt(br.readLine());
// write your code here
boolean[] visited = new boolean[graph.length];
boolean ans = hasPath(graph,src,dest,visited);
System.out.println(ans);
}
}