Skip to content
Advertisement

How to check if a traversion has reached a certain Index in a 2D-Array in Java?

Let’s say we have a 2D-boolean Array as a presentation of a maze, the size of the Array is not fixed and random. The walls are depicted as true:

boolean[][] mazeArray = new boolean[width][height];

The exit of the maze is at a fixed Index. How can I check wether the traversion has reached this certain index or not? My idea was to create an int[ ] to keep track of the position, it gets updated and overwritten with every step:

int[] location = {1,0};

… But I don’t understand why my check in the while-loop doesn’t work:

while( location[0] != (maze[0].length-1) && location[1] != (maze[1].length-2) ) {
   // traversion with pledge algorithm
    }

Advertisement

Answer

The problem with your code is that you check wrong items in your maze array:

  • maze[0] is the first “line” of your 2d-array
  • maze[1] is the second “line” of your 2d-array

Proper way of traversing 2d-array is following (I’ve replaced your location array with separate x and y variables to better visualize the algorithm).

My algorithm enters the 2d mazeArray line by line and then iterates each line’s elements.

public class Maze {
    public static void main(String[] args) {
        int width = 20;
        int height = 20;

        boolean[][] mazeArray = new boolean[width][height];

        int x = 0;
        int y = 0;

        while (y < mazeArray.length) {
            while (x < mazeArray[y].length) {
                System.out.println("Traverse at (" + x + ", " + y + ")");

                x += 1;
            }

            x = 0;
            y += 1;
        }
    }
}

Advertisement