-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.java
114 lines (86 loc) · 2.52 KB
/
search.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//implements several search algorithms that find a path from an initial state to a goal state
import java.util.*;
public class search implements Runnable {
public static enum method {
BFS, DFS, UCS, GS,
A_star {@Override public String toString() {return "A*";}}
}
Queue <state> remainingStates;
method searchMethod;
search(method searchMethod, state startState) {
this.searchMethod = searchMethod;
switch (searchMethod) {
case BFS:
remainingStates = new ArrayDeque <state>();
break;
case DFS:
remainingStates = Collections.asLifoQueue(new ArrayDeque <state>());
break;
case UCS:
remainingStates = new PriorityQueue <state>(11, new UCSComparator());
break;
case GS:
remainingStates = new PriorityQueue <state>(11, new GSComparator());
break;
case A_star:
remainingStates = new PriorityQueue <state>(11, new AStarComparator());
break;
default:
throw new IllegalArgumentException("invalid search method: " + searchMethod);
}
remainingStates.add(startState);
}
//find a path to the goal and print it
public void run() {
System.out.println("searching using " + searchMethod);
System.out.println();
Set <state> visitedStates = new HashSet <state>();
state goal = null;
//search
while (!remainingStates.isEmpty()) {
state curState = remainingStates.remove();
//goal check
if (curState.h() == 0) {
goal = curState;
break;
}
if (visitedStates.add(curState)) //curState has not already been visited
remainingStates.addAll(curState.successors());
}
//print path
if (goal != null)
printPathTo(goal);
else
System.out.println("goal not found");
System.out.println();
}
private void printPathTo(state x) {
int step = 0;
double totalCost = 0;
Queue <state> path = Collections.asLifoQueue(new ArrayDeque <state>());
while (x != null) {
path.add(x);
x = x.parent;
}
for (state i : path) {
System.out.println(step++ + " " + i);
totalCost += i.cost;
}
System.out.println("total path cost: " + totalCost);
}
}
class UCSComparator implements Comparator <state> {
public int compare(state s1, state s2) {
return Double.valueOf(s1.g).compareTo(s2.g);
}
}
class GSComparator implements Comparator <state> {
public int compare(state s1, state s2) {
return Double.valueOf(s1.h()).compareTo(s2.h());
}
}
class AStarComparator implements Comparator <state> {
public int compare(state s1, state s2) {
return Double.valueOf(s1.g + s1.h()).compareTo(s2.g + s2.h());
}
}