迷宫求解器无法找到退出

时间:2016-04-07 23:48:04

标签: java

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;
    }
}

这是我的迷宫类方法checkForExitPath无效或者至少我认为因为每次我使用此跑步者类运行迷宫求解器

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 个答案:

答案 0 :(得分:1)

你的整个方法并不真正起作用。如果左上角有一个1,我从你的代码中解释为步行方式,它会更改为7,你的方法结束时不会递归。
我认为四个递归方法调用应该是第一个if块的一部分,并且不需要其他块。