问题描述
已经用递归的方法写出迷宫了。。。现在要修改成不储存直接打印找到的最终路径就是类似77700000077700这样子的用temp来储存maze,然后调用traverse()publicclassMaze{privatefinalintTRIED=3;privatefinalintPATH=7;privateint[][]grid={{1,1,1,0,1,1,0,0,0,1,1,1,1},{1,0,1,1,1,0,1,1,1,1,0,0,1},{0,0,0,0,1,0,1,0,1,0,1,0,0},{1,1,1,0,1,1,1,0,1,0,1,1,1},{1,0,1,0,0,0,0,1,1,1,0,0,1},{1,0,1,1,1,1,1,1,0,1,1,1,1},{1,0,0,0,0,0,0,0,0,0,0,0,0},{1,1,1,1,1,1,1,1,1,1,1,1,1}};//-----------------------------------------------------------------//Attemptstorecursivelytraversethemaze.Insertsspecial//charactersindicatinglocationsthathavebeentriedandthat//eventuallybecomepartofthesolution.//-----------------------------------------------------------------publicbooleantraverse(introw,intcolumn){booleandone=false;if(valid(row,column)){grid[row][column]=TRIED;//thiscellhasbeentriedif(row==grid.length-1&&column==grid[0].length-1)done=true;//themazeissolvedelse{done=traverse(row+1,column);//downif(!done)done=traverse(row,column+1);//rightif(!done)done=traverse(row-1,column);//upif(!done)done=traverse(row,column-1);//left}if(done)//thislocationispartofthefinalpathgrid[row][column]=PATH;}returndone;}//-----------------------------------------------------------------//Determinesifaspecificlocationisvalid.//-----------------------------------------------------------------privatebooleanvalid(introw,intcolumn){booleanresult=false;//checkifcellisintheboundsofthematrixif(row>=0&&row<grid.length&&column>=0&&column<grid[row].length)//checkifcellisnotblockedandnotpreviouslytriedif(grid[row][column]==1)result=true;returnresult;}//-----------------------------------------------------------------//Returnsthemazeasastring.//-----------------------------------------------------------------publicStringtoString(){Stringresult="n";for(introw=0;row<grid.length;row++){for(intcolumn=0;column<grid[row].length;column++)result+=grid[row][column]+"";result+="n";}returnresult;}}
publicclassMazeSearch{//-----------------------------------------------------------------//Createsanewmaze,printsitsoriginalform,attemptsto//solveit,andprintsoutitsfinalform.//-----------------------------------------------------------------publicstaticvoidmain(String[]args){Mazelabyrinth=newMaze();System.out.println(labyrinth);if(labyrinth.traverse(0,0))System.out.println("Themazewassuccessfullytraversed!");elseSystem.out.println("Thereisnopossiblepath.");System.out.println(labyrinth);}}
解决方案
解决方案二:
楼主这是提问呢还是贴答案呢,没看明白