gpt4 book ai didi

java - 遍历二维数组的下一个元素

转载 作者:行者123 更新时间:2023-12-01 11:58:49 24 4
gpt4 key购买 nike

    //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");
}

您好,鉴于我有这个二维数组,并且我想访问下一个元素,我最终会达到索引越界,是否还有其他解决方法来访问下一个元素?

最佳答案

您必须更仔细地检查您的索引:

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

关于java - 遍历二维数组的下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28134742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com