-
Notifications
You must be signed in to change notification settings - Fork 0
/
PathFinder.java
76 lines (57 loc) · 2.4 KB
/
PathFinder.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
package pathfinding;
import pathfinding.simulation.Board;
import pathfinding.simulation.Player;
import pathfinding.simulation.Simulation;
import pathfinding.util.Utils;
import java.awt.*;
public class PathFinder {
private final static char[] possibleInstructions = new char[] { 's', 'r', 'l', 'n', 'p' };
public static void main(String[] args) {
int[][] playground = new int[][] { //
{ 0, 0, 0, 2, 0, 0, 2 }, //
{ 0, 2, 0, 2, 0, 0, 0 }, //
{ 0, 0, 0, 0, 0, 2, 0 }, //
{ 2, 0, 2, 2, 0, 0, 0 }, //
{ 0, 0, 0, 2, 0, 0, 0 }, //
{ 0, 2, 2, 0, 0, 2, 2 }, //
{ 0, 2, 0, 0, 2, 0, 0 }, //
{ 0, 0, 0, 0, 0, 2, 0 }, //
{ 2, 0, 0, 2, 0, 0, 0 }, //
};
char[] solution = PathFinder.findOptimalSolution(playground, 0, 0, Player.DOWN, 0, 6, 5, 40);
System.out.println(solution);
}
public static char[] findOptimalSolution(int[][] playground, int x, int y, int direction, int blocks, int findX, int findY, int searchLimit) {
int currentTestLength = Utils.getMinimalStepsAndTurns(x, y, direction, findX, findY);
while (currentTestLength <= searchLimit) {
char[] instructions = new char[currentTestLength];
if (findInstructions(playground, x, y, direction, blocks, findX, findY, instructions)) {
return instructions;
}
currentTestLength++;
}
return new char[0];
}
private static boolean findInstructions(int[][] playground, int x, int y, int direction, int blocks, int findX, int findY, char[] instructions) {
Board board = new Board(playground);
Player player = new Player(x, y, direction, blocks);
Point targetPos = new Point(findX, findY);
Simulation simulation = new Simulation(board, player, targetPos);
return findPath(simulation, instructions, 0);
}
public static boolean findPath(Simulation simulation, char[] instructions, int filled) {
if (isImpossibleForCurrentPath(simulation, instructions, filled)) {
return false;
}
for (char possibleInstruction : possibleInstructions) {
if (simulation.willInstructionLeadToTargetPosition(possibleInstruction, instructions, filled)) {
return true;
}
}
return false;
}
private static boolean isImpossibleForCurrentPath(Simulation simulation, char[] instructions, int filled) {
int numberOfInstructionsLeft = instructions.length - filled;
return numberOfInstructionsLeft < Utils.getMinimalStepsAndTurns(simulation);
}
}