-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFID_algo.java
More file actions
102 lines (78 loc) · 2.75 KB
/
Copy pathDFID_algo.java
File metadata and controls
102 lines (78 loc) · 2.75 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
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
/**
*
* @author Boaz Sharabi
*
*This class represent DFID search algo
*https://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search
*/
public class DFID_algo extends search_algo{
String result="";
int depth=1;
boolean isCutoff=false;
public DFID_algo(tile start, tile goal, boolean withOpen, boolean withTime) {
super(start, goal, withOpen, withTime);
}
@Override
public void run() {
StartTime = System.nanoTime();
if(!checkValid(start)) {
saveToFile();
return;
}
// for depth 1 -> infinty
while(true) {
// make openlist
openlist.clear();
// call to limited dfs until depth (every loop depth param icrease by 1)
result= Limited_DFS(start,goal,depth);
// if result = path to goal
if(!result.equals("cutoff")&&!result.equals("fail")) {
saveToFile();
return;
}
// if result = fail (no solution) exit and return "no path"
else if(result.equals("fail")) break;
// if result = "cutoff" increase depth by 1 and search again
depth++;
}
saveToFile();
}
private String Limited_DFS(tile state, tile goal, int limit) {
// if the state is goal return "succses"
if(state.equals(goal)) {
path=path(state); // |
cost =state.getCost(); // |
return "sucsses"; // | the simple base cases of the recursion
} // | "cutoff" , find the goal , "fail"
// |
// |
else if(limit==0)return "cutoff"; // |
// if we reach to limit depth and still no solution found and the algorithm not failed (maybe there is a solution in deeper depth)
// if the tile is no the goal tile and not reach to the limit yet
else {
isCutoff=false;
// insert tile to openlist
openlist.put(state.getKey(), state);
// for each allowed operator on state
for(int i=1; i<5; i++) {
// child= legal_operator(state)
tile child= state.move(i);
// loop avoidence
if(child!=null&&!openlist.containsKey(child.getKey())) {
result= Limited_DFS(child,goal,limit-1); //dfs step
// no solution in correct depth bound
if(result.equals("cutoff")) isCutoff=true;
// if we find a solution
else if(!result.equals("fail")) return result;
}
}
// print openlist to console if needed
if(withOpen) PrintOpenList();
//the memory for state tile should be also released (there no solution in its path)
openlist.remove(state.getKey());
if(isCutoff) return "cutoff";
// We found no solution and were not blocked "cutoff"
else return "fail";
}
}
}