(Easy) BackTracking- Rat in a Maze. LeetCode
Description: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 the destination. The rat can move only in two directions: forward and down. Following is an example maze. Gray blocks are dead ends (value = 0). Following is binary matrix representation of the above maze. {1,0} {1,1,1} {0,1} Following is a maze with highlighted solution path. Following is the solution matrix (output of program) for the above input matrx. {1,0} {0,1} All enteries in solution path are marked as 1. ? Solution:class Main { public static void main(String[] args) { Main rat = new Main(); int maze[][] = { { 1,0 },{ 1,1 },{ 0,1 } }; int [][] sol = new int[4][4]; if(rat.CheckSol(maze,0,sol)){ rat.printSolution(sol); } } void printSolution(int sol[][]) { for (int i = 0; i < sol.length; i++) { for (int j = 0; j < sol[0].length; j++) System.out.print(" " + sol[i][j] + " "); System.out.println(); } } boolean CheckSol(int[][]maze,int i,int j,int[][] sol){ //goal if(i==maze.length-1 && j ==maze[0].length-1){ sol[i][j]=1; return true; } if(isSafe(maze,i,j)){ sol[i][j] = 1; if(CheckSol(maze,i+1,j,sol)){ return true; } if(CheckSol(maze,j+1,sol)){ return true; } sol[i][j]=0; return false; } return false; } boolean isSafe(int[][] maze,int j ){ if((i>=0 &&i<maze.length )&& (j>=0&&j<maze[0].length)&&maze[i][j]==1){ return true; } return false; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |