-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS.java
64 lines (48 loc) · 1.31 KB
/
DFS.java
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
import java.util.LinkedList;
public class DFS extends A1 {
public DFS(int [][] adjacencyMatrix ){
super();
}
public static String dfs(int dep, int dest){ // LIFO queue
boolean[] expanded = new boolean[20];
LinkedList<Integer> queue = new LinkedList<Integer>();
int[] parent = new int[20];
int pointer;
int maxCities = 0;
int x;
int visited=0;
System.out.println("*** Depth First Search ***");
System.out.println("Below is the path");
for(int i=0; i<20; i++){
parent[i] = -1;
}
expanded[dep] = true;
queue.add(dep);
if(dep == dest){ // already at destination city
return ("Already at destination city");
}
while(!queue.isEmpty()){
pointer = queue.removeLast(); //LIFO
visited++;
if(pointer==dest){
System.out.println("Reached " + A1.getCityName(dest));
System.out.println("Visited: " + visited);
return ("Number of cities expanded is (max number of nodes generated): " + maxCities);
}
for(x=0; x<20; x++){
if(adjacencyMatrix[pointer][x] != 0 && expanded[x] == false){
expanded[x] = true;
parent[x] = pointer;
queue.add(x);
}
}
if(queue.size() >0){
System.out.println(A1.getCityName(pointer));
}
if(queue.size()>maxCities){
maxCities = queue.size();
}
}
return "No cities traversed";
}// end dfs
}