Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int prince(int[][] drm, int i, int j) {
- //TODO: remove
- printPrince(drm, "start");
- return prince(drm, i, j, -1);
- }
- public static int prince(int[][] drm, int i, int j, int lastSpot) {
- int count = 0, tempCount = 0, tempCount2 = 0;
- //out of bounders
- if (i < 0 || i >= drm.length || j < 0 || j >= drm.length)
- return -1;
- int spot = drm[i][j];
- //if the evil man is found
- if (spot == -1)
- return 1;
- //already visited
- else if (spot == -2)
- return -1;
- //if jump was too high
- else if(lastSpot > 0 && lastSpot > spot && lastSpot - spot > 2)
- return -1;
- //if climb was too high
- else if (lastSpot > 0 && lastSpot < spot && spot - lastSpot > 1)
- return -1;
- int shortestPath = Integer.MAX_VALUE;
- //The comments of go right apply to go up, down right left as well
- //Go right
- drm[i][j] = -2; // mark the visited spot with -2
- //TODO: remove
- printPrince(drm, "right");
- count = prince(drm, i , j + 1, spot); //go Right
- count = count == -1 ? -1 : count + 1; // if path didn't lead to dead end, add 1 to count
- shortestPath = count != -1 && count < shortestPath ? count : shortestPath; //if this path is the shortest save its count in shortestPath
- drm[i][j] = spot; //change the visited spot back to its original value
- int lastI, lastJ;
- //Go up
- drm[i][j] = -2;
- //TODO: remove
- printPrince(drm, "up");
- count = prince(drm, i - 1, j, spot);
- count = count == -1 ? -1 : count + 1;
- shortestPath = count != -1 && count < shortestPath ? count : shortestPath;
- drm[i][j] = spot;
- //Go down
- drm[i][j] = -2;
- //TODO: remove
- printPrince(drm, "down");
- count = prince(drm, i + 1, j, spot);
- count = count == -1 ? -1 : count + 1;
- shortestPath = count != -1 && count < shortestPath ? count : shortestPath;
- drm[i][j] = spot;
- //Go left
- drm[i][j] = -2;
- //TODO: remove
- printPrince(drm, "left");
- count = prince(drm, i, j - 1, spot);
- count = count == -1 ? -1 : count + 1;
- shortestPath = count != -1 && count < shortestPath ? count : shortestPath;
- drm[i][j] = spot;
- return shortestPath == Integer.MAX_VALUE ? -1 : shortestPath;
- }
- private static void printPrince(int[][] arr, String direction) {
- System.out.println(" ");
- switch (direction) {
- case "start": System.out.println("Start");break;
- case "left": System.out.println("â†"); break;
- case "right": System.out.println("→"); break;
- case "down": System.out.println("↑"); break;
- case "up": System.out.println("↓"); break;
- }
- for(int i = 0; i < arr.length; i ++) {
- for(int j = 0; j < arr.length; j++) {
- if(arr[i][j] == -1 || arr[i][j] == -2)
- System.out.print(arr[i][j] + " | ");
- else
- System.out.print(" " + arr[i][j] + " | ");
- }
- System.out.println(" ");
- }
- System.out.println(" ");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement