public class Maze { // question: give a maze. Find shortest path from left top corner to right bottom corner. // 1 is wall. cannot go thru. int minFoundLen = Integer.MAX_VALUE; int m = 0; int n = 0; public void findPath(int[][] mazePlan){ if(mazePlanPlease help review my code.length == 0) return;
public class Maze { // question: give a maze. Find shortest path from left top corner to right bottom corner. // 1 is wall. cannot go thru. int minFoundLen = Integer.MAX_VALUE; int m = 0; int n = 0; public void findPath(int[][] mazePlan){ if(mazePlan.length == 0) return; m = mazePlan.length; n = mazePlan[0].length; int[][] path = new int[m][n]; helper(mazePlan, 0, 0, 0,path); System.out.println("shortest path is " + minFoundLen); } private void helper(int[][] maze, int x, int y, int pathLen,int[][] path){ if(x < 0 || y < 0 || x >= m || y >= n){ return; } if(path[x][y]!=0){ return; } if(maze[x][y] != 0){ return; } if(x == m-1 && y == n-1){ minFoundLen = Math.min(minFoundLen, pathLen); return; } path[x][y] = 1; helper(maze, x+1,y,pathLen+1,path); helper(maze, x-1,y,pathLen+1,path); helper(maze, x,y+1,pathLen+1,path); helper(maze, x,y-1,pathLen+1,path); path[x][y] = 0; } public static void main(String[] args){ int[][] mazePlan = { {0,1,0,0,0}, {0,0,0,1,0}, {0,0,0,0,0}, {1,1,1,0,0}, {0,0,0,0,0} }; Maze maze = new Maze(); maze.findPath(mazePlan); } } }