-
Notifications
You must be signed in to change notification settings - Fork 0
/
A_star_algo.java
92 lines (74 loc) · 2.57 KB
/
A_star_algo.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
import java.util.HashMap;
import java.util.PriorityQueue;
/**
*
* @author Boaz Sharabi
*
* This class represent A* search algorithm
* https://en.wikipedia.org/wiki/A*_search_algorithm
*/
public class A_star_algo extends heuristic_search_algo {
//more explain on tile_comperator in heuristic_search_algo class file
PriorityQueue<tile> PQ= new PriorityQueue<>(get_tile_comperator());
HashMap<String, tile> CloseList= new HashMap<>();
public A_star_algo(tile start, tile goal, boolean withOpen, boolean withTime) {
super(start, goal, withOpen, withTime);
}
@Override
public int heuristic(tile t) {
return Tile_Heuristic.Manethen_Distance(t);
}
@Override
public void run() {
StartTime = System.nanoTime();
if(!checkValid(start)) {
saveToFile();
return;
}
// insert the intial state to openlist and priority queue
openlist.put(start.getKey(),start);
PQ.add(start);
while(!PQ.isEmpty()) {
// print openlist to console if needed
if(withOpen) PrintOpenList();
// remove the state with lowest f(n) - f(n) = h(n) + g(n) / more explain in heuristic_search_algo class file
tile state=PQ.poll();
openlist.remove(state.getKey());
// if we find the goal state return the solution
if(state.equals(goal)) {
path=path(state);
count=ColorTilePuzzle.count;
cost =state.getCost();
saveToFile();
return;
}
// insert the state to closelist
CloseList.put(state.getKey(), state);
//for each allowed operator on n do: {
for(int i=1;i<5;i++) {
tile child= state.move(i);
if(child!=null) {
// insert the state to the queue(and to openlist) if it not in openlist and not in closelist
if(!CloseList.containsKey(child.getKey())&&!openlist.containsKey(child.getKey())) {
PQ.add(child);
openlist.put(child.getKey(), child);
}
else {
// check if there same tile in openlist/priority queue
tile same=openlist.get(child.getKey());
// if we find this "child" state has cheaper path from initial state than same state already in openlist
// take out the state with the expensive path from openlist and insert the state with the cheap path
if(same!=null&&same.getCost()>child.getCost()) {
PQ.remove(same);
openlist.remove(child.getKey());
openlist.put(child.getKey(), child);
PQ.add(child);
}}
}
}
//end for each allowed operator }
}
// there is no solution - check how much tiles generated and return "no path"
saveToFile();
}
}