[英]Array index out of bounds for 3d maze
即時通訊使用arraylists編寫3d迷宮。 我檢查我是否正在移動的6種方式是否打開的部分總是給我一個數組索引超出范圍的異常,我不知道為什么。
我曾嘗試將td更改為其他內容,因為我認為這是導致問題的地方,但沒有奏效
class Step{
int r;
int c;
int d;
int dir;
public Step(int d, int c, int r) {
this.r = r;
this.c = c;
this.d = d;
this.dir = 0;
}
}
public class MMaze {
public static void main (String[] args) throws Exception {
int[][][] maze = new int[][][]{
{
{0,0,1,1,1,1},
{0,0,1,1,1,1},
{0,0,0,0,1,1},
{1,0,0,1,1,0}
}, {
{0,0,1,1,1,1},
{1,1,0,0,1,1},
{1,1,0,0,1,1},
{0,0,0,1,1,0}
}, {
{0,0,0,0,0,0},
{1,1,1,1,0,0},
{1,1,0,0,0,0},
{1,1,1,1,0,0}
}
};
int[][][] next = new int[][][] {
{
{0, 0, 1}, //right
{0, 1, 0}, //down
{0, 0, -1}, //left
{0, -1, 0}, //up
{1, 0, 0}, //forward
{-1, 0, 0} //backward
}
};
Step start = new Step(0,0,0);
//Step end = new Step(2,3,5);
Stack<Step> s = new Stack<>();
s.push(start);
while(!s.isEmpty()){
Step t = s.peek();
t.dir++;
if (t.dir > 6){
s.pop();
} else if (maze[t.d + next[0][t.dir - 1][0]][t.r + next[0][t.dir - 1][1]][t.c + next[0][t.dir - 1][2]] == 0) { //this part is causing the error
Step a = new Step(t.d + next[0][t.dir - 1][0], t.r + next[0][t.dir - 1][1], t.c + next[0][t.dir - 1][2]);
if (!isStepInStack(s, a)) {
s.push(a);
if(isStepEnd(a)) {
print(s);
s.pop();
}
}
}
}
}
public static void print(Stack<Step> s) {
System.out.println("one answer is:");
for (Step var : s) {
System.out.println(var.d + "." + var.r + "." + var.c);
}
System.out.println();
}
public static boolean isStepInStack(Stack<Step> stack, Step step) {
for (Step var : stack) {
if(step.r == var.r && step.c == var.c && step.d == var.d) {
return true;
}
}
return false;
}
public static boolean isStepEnd(Step step) {
if (step.r == 3 && step.c == 5 && step.d == 2) {
return true;
}
return false;
}
}
我希望打印出迷宮的出路,現在出現索引錯誤
我是否可以建議強制執行長度檢查(無論如何,這都是一個好習慣),然后在else語句上放一些東西,它將記錄您的當前狀態以及您嘗試訪問的內容-我現在可以診斷您的代碼,但我覺得您會有更多受益於上述
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.