0
    //add adj nodes
    try{
        for(int r2 = 0; r2 < rows; r2++){
            for(int c2 = 0; c2 < cols; c2++){
                Node currentNode = nodeGrid[r2][c2];
                Node rightNode = nodeGrid[r2][c2+1];
                Node bottomNode = nodeGrid[r2+1][c2];

                if(!rightNode.isWall()){
                    currentNode.addNeighbor(rightNode);
                }
                if(!bottomNode.isWall()){
                    currentNode.addNeighbor(bottomNode);
                }
            }
        }
    }catch(ArrayIndexOutOfBoundsException e){
        System.out.println("no next node");
    }

Hello, given that i have this 2D array, and i would like to access the next element i would eventually reach a index out of bounds, is there any other workaround for accessing the next element?

1
  • Test if there is a right element before accessing it: if (c2 + 1 < cols) Commented Jan 25, 2015 at 8:52

1 Answer 1

1

You must check your indices more carefully :

    for(int r2 = 0; r2 < rows; r2++){
        for(int c2 = 0; c2 < cols; c2++){
            Node currentNode = nodeGrid[r2][c2];
            Node rightNode = null;
            if (c2 < cols - 1) // the condition for the existence of a right node
                rightNode = nodeGrid[r2][c2+1];
            Node bottomNode = null;
            if (r2 < rows - 1) // the condition for the existence of a bottom node
                bottomNode = nodeGrid[r2+1][c2];

            if(rightNode != null && !rightNode.isWall()){
                currentNode.addNeighbor(rightNode);
            }
            if(bottomNode != null && !bottomNode.isWall()){
                currentNode.addNeighbor(bottomNode);
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.