数组越界如何解决呢?

题目:读入两个整数m,n,输出一个m行n列的矩阵,这个矩阵是1~mn这些自然数按照右、下、左、上螺旋填入的结果。
public static void main(String[] args) {

    int row=6;
    int col=7;
    int dest[][] = new int[row][col];

注释块的解释:下面两个for循环 在目的数组的外层再套-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;
}

}

阅读 3.5k
2 个回答

同意楼上观点、第二遍循环会导致越界。

越界是这个函数:circlePrint 里的问题。

第一次调用 circlePrint(arr,1,1,0)
第二次调用 0,1,1
这里就越界了:

 if (arr[i][j + 1] == 0) {// 向右走  arr[0][2]==0
            if (arr[i - 1][j] == 0) {// 向上走  if(arr[-1][1]==0) ,这里就越界了
            ...
            }
  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题