Repository navigation
Expand file tree
/
Copy pathHasPath.java
More file actions
79 lines (54 loc) · 1.58 KB
/
Copy pathHasPath.java
File metadata and controls
79 lines (54 loc) · 1.58 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.*;
import java.util.*;
public class HasPath{
static class Edge{
int src;
int nbr;
int dst;
// constructor
Edge(int src, int nbr, int dst){
this.src = src;
this.nbr = nbr;
this.dst = dst;
}
}
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];
// initialize the empty array list
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());
boolean visited[] = new boolean[vtces];
boolean ans = hasPath(graph, src, dest, visited);
System.out.println(ans);
}
public static boolean hasPath(ArrayList<Edge>[] graph, int src, int dest, boolean visited[]){
// base condition
if(src==dest){
return true;
}
visited[src] = true;
for(Edge e: graph[src]){
if(visited[e.nbr] == false){
boolean hasN = hasPath(graph, e.nbr, dest, visited);
if(hasN==true){
return true;
}
}
}
return false;
}
}