A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down.
In the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with limited number of moves.
Refer : http://www.geeksforgeeks.org/archives/13376
In the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with limited number of moves.
public class RatMaze {
public static void main(String[] args) {
int[][] maze = {
{ 1, 0, 0, 0 },
{ 1, 1, 0, 1 },
{ 0, 1, 0, 0 },
{ 1, 1, 1, 1 }
};
int m = maze.length;
int n = maze[0].length;
int[][] solution = new int[m][n];
boolean isSolutionAvailable = getSolution(maze, solution, 0, 0);
if (isSolutionAvailable) {
printMatrix(solution);
} else {
System.out.println("Solution is not available");
}
}
private static void printMatrix(int[][] a) {
System.out.println();
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(" " + a[i][j] + " ");
}
System.out.println();
}
}
private static boolean getSolution(int[][] maze, int[][] solution, int i,
int j) {
int m = maze.length;
int n = maze[0].length;
if (i < 0 || i >= m || j < 0 || j >= n || maze[i][j] == 0) {//check if path is blocked
return false;
}
if (i == m - 1 && j == n - 1) {
solution[i][j] = 1;
return true;
}
// At each position look in forward and downward direction.
if (getSolution(maze, solution, i, j + 1)
|| getSolution(maze, solution, i + 1, j)) {
solution[i][j] = 1;
return true;
}
return false;
}
}
Refer : http://www.geeksforgeeks.org/archives/13376
No comments:
Post a Comment