-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS.java
63 lines (47 loc) · 1.31 KB
/
BFS.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
import java.util.LinkedList;
public class BFS extends A1{
public BFS(int [][] adjacencyMatrix ){
super();
}
public static String bfs(int dep, int dest){ //FIFO
boolean[] expanded = new boolean[20];
LinkedList<Integer> queue = new LinkedList<Integer>();
int[] parent = new int[20];
int pointer;
int maxCities = 0;
int visited = 0;
System.out.println("*** Breadth 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.removeFirst(); //FIFO queue
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(int 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 "Did not traverse any cities";
}// end bfs
}