-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVacuumBSF.java
More file actions
65 lines (55 loc) · 2.09 KB
/
VacuumBSF.java
File metadata and controls
65 lines (55 loc) · 2.09 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
import java.util.*;
class VacuumBFS {
// Constant arrays to look up the result of applying an action to a given state.
// For example, looking up state 1 in the actionRight array gives state 2
// which is the result of moving right from state 1 (see the diagram in
// unit 2.8)
static int[] actionLeft={1,1,3,3,5,5,7,7};
static int[] actionRight={2,2,4,4,6,6,8,8};
static int[] actionSuck={3,6,3,8,7,6,7,8};
// Returns true when s is a goal state.
static boolean goalTest(int s) {
return (s==7 || s==8);
}
// Returns true if there is a solution, i.e. a path from state 1 to 7 or 8.
static boolean BFS() {
int initialState=1;
if(goalTest(initialState)) {
return true;
}
// frontier initially contains just 1.
ArrayList<Integer> frontier=new ArrayList<Integer>();
frontier.add(1);
// frontier will be used as a FIFO queue to implement BFS.
// explored is initially empty.
ArrayList<Integer> explored=new ArrayList<Integer>();
while(true) {
if(frontier.size()==0) {
// There are no more nodes to expand, and we did not find a goal.
return false;
}
// Remove the first element of frontier
int node=frontier.remove(0);
explored.add(node);
// Expand 'node'
// Make children array containing the three states that
// result from applying the three actions to the current state.
int[] children = {actionLeft[node], actionRight[node], actionSuck[node]};
for(int child : children) {
if(goalTest(child)) {
System.out.println("Solution found!");
return true;
}
if( !frontier.contains(child) && !explored.contains(child) ) {
// This state has not been seen before.
// Add it to the end of the frontier list.
frontier.add(child);
}
}
}
}
public static void main(String args []) {
boolean solutionFound=BFS();
System.out.println("Solution found: "+solutionFound);
}
}