|
| 1 | +package me.ramswaroop.backtracking; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by IntelliJ IDEA. |
| 5 | + * |
| 6 | + * @author: ramswaroop |
| 7 | + * @date: 10/18/15 |
| 8 | + * @time: 10:39 AM |
| 9 | + */ |
| 10 | +public class RatInAMaze { |
| 11 | + |
| 12 | + public static boolean isValidMove(int i, int j, int[][] maze) { |
| 13 | + if (i >= 0 && i < maze.length && j >= 0 && j < maze[0].length && maze[i][j] == 1) { |
| 14 | + return true; |
| 15 | + } else { |
| 16 | + return false; |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + public static boolean isValidPath(int i, int j, int[] xMoves, int[] yMoves, int[][] maze, int[][] path) { |
| 21 | + |
| 22 | + if (i == maze.length - 1 && j == maze[0].length - 1) return true; |
| 23 | + |
| 24 | + int nextI, nextJ; |
| 25 | + |
| 26 | + for (int k = 0; k < xMoves.length; k++) { |
| 27 | + nextI = i + xMoves[k]; |
| 28 | + nextJ = j + yMoves[k]; |
| 29 | + if (isValidMove(nextI, nextJ, maze)) { |
| 30 | + path[nextI][nextJ] = 1; |
| 31 | + if (isValidPath(nextI, nextJ, xMoves, yMoves, maze, path)) { |
| 32 | + return true; |
| 33 | + } else { |
| 34 | + path[nextI][nextJ] = 0; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + public static void printMazePath(int i, int j, int[][] maze) { |
| 42 | + |
| 43 | + int[] xMoves = {0, 1}; |
| 44 | + int[] yMoves = {1, 0}; |
| 45 | + |
| 46 | + int[][] path = new int[maze.length][maze[0].length]; |
| 47 | + |
| 48 | + System.out.println("Maze"); |
| 49 | + System.out.println("---------------"); |
| 50 | + print2DMatrix(maze); |
| 51 | + System.out.println("---------------"); |
| 52 | + |
| 53 | + if (isValidPath(i, j, xMoves, yMoves, maze, path)) { |
| 54 | + print2DMatrix(path); |
| 55 | + } else { |
| 56 | + System.out.println("No escape path found!"); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + public static void print2DMatrix(int[][] array) { |
| 61 | + for (int i = 0; i < array.length; i++) { |
| 62 | + for (int j = 0; j < array[0].length; j++) { |
| 63 | + System.out.print("[" + array[i][j] + "]"); |
| 64 | + } |
| 65 | + System.out.println(); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public static void main(String a[]) { |
| 70 | + printMazePath(0, 0, new int[][]{{1, 1, 1, 1}, {0, 0, 1, 1}}); |
| 71 | + } |
| 72 | +} |
0 commit comments