当我去掉已经注释的代码时,就会发生数组越界,这是为什么呢????
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;
}
}