簡體   English   中英

避免二維數組中的越界異常

[英]Avoid out of bounds exception in 2D array

我正在嘗試解決一個使用二維數組的問題,即迷宮中的老鼠問題。

在檢查試圖編譯的條件時,它發現一個數組索引越界異常......我如何檢查值以使其不超出數組邊界?

static void solveMaze(){

    int nSteps = 0; // Number of steps.
    int x = 0; int y = 0; // Starting point.

    boolean mazeCompleted = false;

    while (!mazeCompleted){

        if(x == maze.mazeMatrix.length && y == maze.mazeMatrix.length)
            mazeCompleted = true;

        else if(maze.mazeMatrix[x+1][y] == 0){ // Move right.
            maze.mazeMatrix[x+1][y] = 2;
            x++; nSteps++;
        }

        else if(maze.mazeMatrix[x-1][y] == 0){ // Move left.
            maze.mazeMatrix[x-1][y] = 2;
            x--; nSteps++;
        }

        else if(maze.mazeMatrix[x][y+1] == 0){ // Move down.
            maze.mazeMatrix[x][y+1] = 2;
            y++; nSteps++;
        }

        else if(maze.mazeMatrix[x][y-1] == 0){ // Move up.
            maze.mazeMatrix[x][y-1] = 2;
            y--; nSteps++;
        }

    }

    maze.printMatrix();
    System.out.println("Maze COMPLETE! - With a total of " + nSteps + " steps.");

}

之前嘗試過使用兩個“for”循環來防止越界,但我無法解決這個問題。

您的程序中有一個非常關鍵的錯誤。 你永遠不會到達迷宮的盡頭!

if(x == maze.mazeMatrix.length && y == maze.mazeMatrix.length)

引用越界的索引! 它應該是

if(x == maze.mazeMatrix.length - 1 && y == maze.mazeMatrix.length - 1)

在嘗試搬到那里之前,您還需要檢查是否可以並且應該搬家。 IE :

while (!mazeCompleted){

boolean moveRight = (x + 1 < mazeMatrix.length && maze.mazeMatrix[x+1][y] == 0 ? true : false);
boolean moveLeft = (x - 1 >= 0 && maze.mazeMatrix[x-1][y] == 0 ? true : false);
boolean moveUp = (y + 1 < mazeMatrix[x].length && maze.mazeMatrix[x][y+1] == 0 ? true : false);
boolean moveDown = (y - 1 >= 0 && maze.mazeMatrix[x][y-1] == 0 ? true : false);

和:

else if(moveRight) { // Move right.
        maze.mazeMatrix[x+1][y] = 2;
        x++; nSteps++;
}

等等。雖然看起來這確實是應該遞歸解決的問題,但好像迷宮中有任何循環一樣,你最終會卡住並無限循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM