0

所以我正在尝试做一个简单的迷宫求解器(深度优先)。我不想帮助解决递归方法,但由于某种原因,这会导致 NullPointerException 对单元格的 ArrayList 的 .add 产生影响,谁能帮我知道为什么?(MazeExample 类制作了一个简单的指向 NSEW 的指针迷宫,由我的老师提供,因此我们可以尝试测试我们的代码)。

public static void main(String[] args)
{
    MazeSolver solver = new MazeSolver();
    ExampleMaze example = new ExampleMaze();

    System.out.println(solver.stepsToSolveMaze(example.getStart()));    

}

这是主要的,这里是 MazeSolver 对象(到目前为止,它只计算到最后的移动次数,一次一步)。

public class MazeSolver 
{
private int steps=0;
private ArrayList<MazeCell> visitedCells;
private Deque<MazeCell> breadCrumbs;

public int stepsToSolveMaze(MazeCell cell)
{
    visitedCells.add(cell); //this is where the exception is getting thrown.
    breadCrumbs.push(cell);

    if (cell.isFinish())
    {
        return 1;
    }


    if (cell.east() != null && !visitedCells.contains(cell.east()))
    {
        steps += stepsToSolveMaze(cell.east());
    }
    if (cell.south() != null && !visitedCells.contains(cell.south()))
    {
        steps += stepsToSolveMaze(cell.south());
    }
    if (cell.west() != null && !visitedCells.contains(cell.west()))
    {
        steps += stepsToSolveMaze(cell.west());
    }
    if (cell.north() != null && !visitedCells.contains(cell.north()))
    {
        steps += stepsToSolveMaze(cell.north());
    }
    else
    {
        steps--;
        stepsToSolveMaze(breadCrumbs.pop());            
    }

    return steps;

}
4

2 回答 2

1

在您的示例中,visitedCells 从未设置,因此当您尝试向其中添加项目时,它会导致 NullPointerException。您需要在使用它之前对其进行初始化:

visitedCells = new ArrayList<MazeCell>();

On another point, breadCrumbs will have the same problem, so you should probably initialise that while your at it:

breadCrumbs = new Deque<MazeCell>();
于 2013-03-18T07:17:13.257 回答
1

You are not initializing array List.

Add following in stepsToSolveMaze

visitedCells = new ArrayList<MazeCell>();

and then add elements

于 2013-03-18T07:17:18.093 回答