繁体   English   中英

3D迷宫的数组索引超出范围

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM