【发布时间】:2019-09-02 19:46:44
【问题描述】:
我正在使用 arraylists 编写一个 3d 迷宫。我检查我进入的 6 种方式是否打开的部分总是给我一个数组索引超出范围异常,我不知道为什么。
我尝试将 t.d 更改为不同的东西,因为我认为这是导致问题的原因,但它不起作用
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;
}
}
我希望打印出迷宫的出路,现在出现索引超出范围的错误
【问题讨论】:
标签: java 3d indexoutofboundsexception maze