-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathInDirectedGraph.java
More file actions
62 lines (45 loc) · 1.64 KB
/
pathInDirectedGraph.java
File metadata and controls
62 lines (45 loc) · 1.64 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
import java.util.*;
import java.io.*;
// You are given nodes starting from 1 to A
// Find if a path exists between Nodes 1 and A.
// Start your search from the node 1.
// Return 1 if path exists, else return 0.
public class pathInDirectedGraph {
static ArrayList<Integer> visited;
static public int solve(int A, ArrayList<ArrayList<Integer>> B) {
Queue<Integer> qu = new LinkedList<>();
qu.add(1);
visited = new ArrayList<>();
while(!qu.isEmpty()){
int num = qu.remove();
if(visited.contains(num)) continue;
if(num == A) return 1;
visited.add(num);
ArrayList<Integer> nodes = B.get(num-1);
if(nodes.isEmpty()) continue;
for(int k: nodes){
qu.add(k);
}
}
return 0;
}
public static void main(String[] args) throws IOException {
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
int t, n;
System.out.println("Enter number of nodes: ");
t = Integer.parseInt(infile.readLine());
for(int i=0; i<t; i++){
graph.add(new ArrayList<>());
}
System.out.println("Enter number of edges: ");
n = Integer.parseInt(infile.readLine());
for(int j=0; j<n; j++) {
String[] inp = infile.readLine().split(" ");
graph.get(Integer.parseInt(inp[0])-1).add(Integer.parseInt(inp[1]));
}
//System.out.println(graph);
System.out.println(solve(t, graph));
infile.close();
}
}