-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
QuestionDP.java
79 lines (63 loc) · 2.09 KB
/
QuestionDP.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
package Question9_2;
import java.util.ArrayList;
import java.util.Hashtable;
import java.awt.*;
import CtCILibrary.AssortedMethods;
public class QuestionDP {
public static int size = 4;
public static int[][] maze = new int[size][size];
public static boolean isFree(int x, int y) {
if (maze[x][y] == 0) {
return false;
} else {
return true;
}
}
public static boolean getPath(int x, int y, ArrayList<Point> path) {
// If out of bounds or not available, return.
if (y < 0 || x < 0 || !isFree(x, y)) {
return false;
}
boolean isAtOrigin = (x == 0) && (y == 0);
// If there's a path from the start to my current location, add my location.
if (isAtOrigin || getPath(x, y - 1, path) || getPath(x - 1, y, path)) {
Point p = new Point(x, y);
path.add(p);
return true;
}
return false;
}
public static boolean getPath(int x, int y, ArrayList<Point> path, Hashtable<Point, Boolean> cache) {
/* If out of bounds or not available, return.*/
if (y < 0 || x < 0 || !isFree(x, y)) {
return false;
}
Point p = new Point(x, y);
/* If we've already visited this cell, return. */
if (cache.containsKey(p)) {
return cache.get(p);
}
boolean isAtOrigin = (x == 0) && (y == 0);
boolean success = false;
/* If there's a path from the start to my current location, add my location.*/
if (isAtOrigin || getPath(x, y - 1, path, cache) || getPath(x - 1, y, path, cache)) {
path.add(p);
success = true;
}
cache.put(p, success); // Cache result
return success;
}
public static void main(String[] args) {
maze = AssortedMethods.randomMatrix(size, size, 0, 5);
AssortedMethods.printMatrix(maze);
ArrayList<Point> path = new ArrayList<Point>();
Hashtable<Point, Boolean> cache = new Hashtable<Point, Boolean>();
boolean success = getPath(size - 1, size - 1, path, cache);
if (success) {
String s = AssortedMethods.listOfPointsToString(path);
System.out.println("Path: " + " " + s);
} else {
System.out.println("No path exists.");
}
}
}