跟踪迷宫中的路径

时间:2017-03-08 04:11:21

标签: java recursive-backtracking

程序正在使用回溯来找出迷宫的方法(它做得很好)。当我尝试打印出我所采用的正确路径时,会出现问题。 这是我的solveMaze()方法。

    boolean result = false;        
    while(result==false){
        if((row > 29) || (row < 0) || (col > 19) || (col < 0)) //check if position is within the array
            return false;
        if(maze[row][col].getVar().equals("E")) // check if youre at the exit
            return true;
        if(maze[row][col].getVar().equals("1")) // check if youre hitting a wall
            return false;
        if(maze[row][col].position.size() > 2){ // check if youre at an intersection
            intersection[numIntersection] = maze[row][col]; // add intersection to intersection array
            numIntersection++;                
        }
        //this section does not need to be checked if youve never visited the position before
        if(maze[row][col].getVisted() == true && numIntersection > 0){  
            if(intersection[numIntersection-1] == null)
                return false;
            else if(intersection[numIntersection-1] != null){ //as you backtrack to the last intersection pick up your "markers"
                maze[row][col].setVar("0");
            if(maze[row][col].position == intersection[numIntersection-1].position && intersection[numIntersection-1].getVisted()==true){ //remove intersection from the array as you pass back thru
                maze[row][col].setVar("+");
                intersection[numIntersection-1] = null;
                numIntersection--;
                } 
            }
        }
        if(maze[row][col].position.empty()==true) //check if the stack is empty
            return false;       
        maze[row][col].position.pop();
        if(maze[row][col].getVisted() == false)
            maze[row][col].setVar("+"); //mark path as you land on unvisted positions

        maze[row][col].setVisted(true);

         //look north
        if(solveMaze(row-1,col)== true)  
            return true;           
        //look east
        if(solveMaze(row,col+1)== true){  
            return true;
        }
        //look west
        if(solveMaze(row,col-1)== true){   
            return true;
        }                
        //look south
        if(solveMaze(row+1,col)== true){  
            return true;
        }   
    }

    return false;
}

当我回溯时,我正在挑选我的标记,但它似乎也在正确的路径上拾取标记并打印出一条破碎路径的迷宫。

0 个答案:

没有答案