-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.java
More file actions
73 lines (66 loc) · 1.8 KB
/
DFS.java
File metadata and controls
73 lines (66 loc) · 1.8 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
import java.util.Scanner;
import java.io.*;
import java.lang.*;
import java.util.*;
class DFS{
public static void main(String[] args){
//Set up variables
DFS searcher = new DFS();
Scanner in = new Scanner(new InputStreamReader(System.in));
int vertices = in.nextInt();
int edges = in.nextInt();
HashMap<Integer,LinkedList> graph = new HashMap<Integer,LinkedList>();
boolean[] visited = new boolean[vertices+1];
Integer v1;
Integer v2;
//Build a graph
for(int i = 0; i < edges; i++){
v1 = new Integer(in.nextInt());
v2 = new Integer(in.nextInt());
visited[v1.intValue()] = false;
visited[v2.intValue()] = false;
LinkedList list1 = new LinkedList();
LinkedList list2 = new LinkedList();
if(graph.containsKey(v1)){
list1 = graph.get(v1);
list1.add(v2);
graph.put(v1,list1);
}
if(graph.containsKey(v2)){
list2 = graph.get(v2);
list2.add(v1);
graph.put(v2,list2);
}
if(!graph.containsKey(v1)){
list1.add(v2);
graph.put(v1,list1);
}
if(!graph.containsKey(v2)){
list2.add(v1);
graph.put(v2,list2);
}
}
//Search for a path
Integer u = new Integer(in.nextInt());
Integer v = new Integer(in.nextInt());
searcher.explore(u, graph, visited);
//Print 1 if a path is found, 0 otherwise
if(visited[v.intValue()] == true)
System.out.println(1);
else System.out.println(0);
}
public void explore(Integer u, HashMap<Integer,LinkedList> graph, boolean[] visited){
visited[u.intValue()] = true;
LinkedList list = new LinkedList();
if(graph.containsKey(u)){
list = graph.get(u);
int listSize = list.size();
Iterator<Integer> iter = list.iterator();
for(int i = 0; i < listSize; i++){
Integer cur = iter.next();
if(visited[cur.intValue()] == false)
this.explore(cur, graph, visited);
}
}
}
}