我在Java中声明了2D数组的向量。在每一步,我都通过add()方法将数组添加到vector中。但是,当打印出此向量以查看内部内容时,我得到了意外的输出。这些数组均未添加数据。 我的代码:
static Vector<int[][]> latinSquare;
static int[][] square;
static int[][] maskRow, maskCol;
static int[] extractCoor(int x, int n) {
int[] ans = new int[2];
ans[0] = x / n;
ans[1] = x % n;
return ans;
}
static void backtrack(int pos, int n) {
int[] coor = extractCoor(pos, n);
int x = coor[0], y = coor[1];
for (int candidate = 0; candidate < n; candidate++) {
if (maskRow[x][candidate] == 0 && maskCol[y][candidate] == 0) {
square[x][y] = candidate;
if (pos == n * n - 1) {
latinSquare.add(square);
printArr(square, n, n);
} else {
maskRow[x][candidate] = 1;
maskCol[y][candidate] = 1;
backtrack(pos + 1, n);
maskRow[x][candidate] = 0;
maskCol[y][candidate] = 0;
}
}
}
}
当我打印出square
时,我得到了正确的拉丁方尺寸n = 3的列表。
0 1 2
1 2 0
2 0 1
0 1 2
2 0 1
1 2 0
0 2 1
1 0 2
2 1 0
0 2 1
2 1 0
1 0 2
1 0 2
0 2 1
2 1 0
1 0 2
2 1 0
0 2 1
1 2 0
0 1 2
2 0 1
1 2 0
2 0 1
0 1 2
2 0 1
0 1 2
1 2 0
2 0 1
1 2 0
0 1 2
2 1 0
0 2 1
1 0 2
2 1 0
1 0 2
0 2 1
但是当我打印出向量latinSquare
时,输出错误:
static void latinSquareBuilder(int n) {
latinSquare = new Vector<int[][]>();
maskRow = new int[n][n];
maskCol = new int[n][n];
square = new int[n][n];
backtrack(0, n);
for (int i = 0; i < latinSquare.size(); i++)
printArr(latinSquare.get(i), n, n);
}
static void printArr(int[][] arr, int n, int m) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.err.print(arr[i][j] + " ");
}
System.err.println();
}
System.err.println();
}
输出:
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1
2 1 0
1 2 2
0 2 1