yiweiyu1438 2019-11-07 19:58 采纳率: 0%
浏览 222

数组越界问题????

当我去掉已经注释的代码时,就会发生数组越界,这是为什么呢????

public static void main(String[] args) {      
                int row=6;
        int col=7;
        int dest[][] = new int[row][col];
        //注释块的解释:在目的数组的外层再套-1   如果不在外层套上-1   则数组越界???
      /*for(int i=0;i<col;i++) {
            dest[0][i]=-1;
            dest[row-1][i]=-1;
        }
        for(int i=0;i<row;i++) {
            dest[i][0]=-1;
            dest[i][col-1]=-1;
        }*/
        circlePrint(dest, 1, 1, 0);
        //遍历目的数组
        for (int i = 1; i < dest.length-1; i++) {
            for (int j = 1; j < dest[i].length-1; j++) {
                System.out.print(dest[i][j] + "\t");
            }
            System.out.println();
        }   
}
    //递归  回溯
    public static boolean circlePrint(int arr[][],int i,int j,int n) {
        if(arr[i][j]==0) {
            n++;
            arr[i][j]=n;
            if (arr[i][j + 1] == 0) {// 向右走
                if (arr[i - 1][j] == 0) {// 向上走
                    circlePrint(arr, i - 1, j, n);
                    return true;
                }
                circlePrint(arr, i, j + 1, n);
                return true;
            }
            if (arr[i + 1][j] == 0) {// 向下走
                circlePrint(arr, i + 1, j, n);
                return true;
            }
            if (arr[i][j - 1] == 0) {// 向左走
                circlePrint(arr, i, j - 1, n);
                return true;
            }
            if (arr[i - 1][j] == 0) {// 向上走
                circlePrint(arr, i - 1, j, n);
                return true;
            }
        }
        return false;
    }
}
  • 写回答

2条回答 默认 最新

  • 到底有多少个小谢 2019-11-08 09:46
    关注

    数组的下标都是从0到长度减一,你这个二维数组的,第一维长度为6,下标则是0到5,第二维长度为7,下标是0到6。

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘