迷宫求解器找不到出口


import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class Maze
{
    private int[][] maze;
    private boolean exitFound;
    public Maze()
    {
        exitFound = false;
        maze = new int[0][0];
    }
    public Maze(int size, String line)
    {
        exitFound=false;
        maze = new int[size][size];
        int spot=0;
        for(int r= 0; r<maze.length; r++)
        {
            for(int c =0; c<maze[r].length; c++)
            {
                maze[r][c]=(line.charAt(spot*2)-48);
                spot++;
            }
        }
    }
    public void checkForExitPath(int r, int c)
{
    if (r >= 0 && r <maze.length &&c >= 0 && c < maze[0].length && maze[r][c] == 1)
    {
        checkForExitPath(r + 1, c);
        checkForExitPath(r - 1, c);
        checkForExitPath(r, c + 1);
        checkForExitPath(r, c - 1);
        maze[r][c] = 7;  
        if (r == maze.length-1 && c == maze[0].length-1){
            this.exitFound =true;
        }
    }
}
    public String toString()
    {
        String hol = "";
        for(int i = 0; i<maze.length; i++){
            for(int j = 0; j<maze[0].length; j++){
                hol += " ";
                if(maze[i][j] == 7){
                    hol += "1";
                }
                else
                {
                    hol += maze[i][j];
                }
            }
            hol += "n";
        }
        if(this.exitFound)
        {
            hol+= "exit found";
        }
        else {
            hol += "exit not found";
        }
        return hol;
    }
}
那是我的迷宫类,

方法检查退出路径不起作用,或者至少我认为是因为每次我用这个运行器类运行迷宫求解器

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class MazeRunner
{
    public static void main( ) throws IOException
    {
        Scanner file = new Scanner(new File("maze.dat"));
        while(file.hasNext())
        {
            int size = file.nextInt();
            file.nextLine();
            Maze test = new Maze(size, file.nextLine());
            test.checkForExitPath(0,0);
            out.println(test);
        }
    }
}

我得到的唯一输出是找不到出口,但我可以找到出口。我正在递归地执行此操作。

你的整个方法并没有真正递归地工作。如果左上角有一个 1,我从您的代码中将其解释为可步行的方式,则将其更改为 7,并且您的方法在没有递归的情况下结束。
我认为四个递归方法调用应该是第一个 if 块的一部分,不需要其他块。

最新更新