【发布时间】:2021-11-10 03:02:40
【问题描述】:
n-queens 谜题是将 n 个皇后放在 (n×n) 棋盘上,使得没有两个皇后可以互相攻击。
我使用回溯来解决问题。但是我遇到了一个奇怪的问题。
下面是我写的代码:
import java.util.ArrayList;
public class NQueenProblem {
static ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
static ArrayList<ArrayList<Integer>> nQueen(int n) {
ArrayList<Integer> positions = new ArrayList<Integer>();
//boolean[][] placed = new boolean[n][n];
solveNQueenRec(n, 0, new boolean[n][n], positions);
//for dubugging purpose. This prints empty arrays. not able to understand why?
for (ArrayList<Integer> list : ans)
System.out.println(list);
return ans;
}
static void solveNQueenRec(int n, int col, boolean[][] placed, ArrayList<Integer> positions) {
if (col == n) {
//for debugging process
System.out.println("Adding " + positions);
ans.add(positions);
System.out.println("Added " + positions);
}
for (int row = 0; row < n && col < n; row++) {
if (isSafe(row, col, placed, n)) {
placed[row][col] = true;
positions.add(row + 1);
solveNQueenRec(n, col + 1, placed, positions);
placed[row][col] = false;
positions.remove(positions.size() - 1);
}
}
// return null;
}
private static boolean isSafe(int row, int col, boolean[][] placed, int n) {
boolean safe = true;
// checking if exists in same row
for (int i = 0; i < col; i++) {
if (placed[row][i])
safe = false;
}
// checking for upper diagonal
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (placed[i][j])
safe = false;
}
// checking for lower diagonal
for (int i = row, j = col; i < n && j >= 0; i++, j--) {
if (placed[i][j])
safe = false;
}
return safe;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nQueen(4);
}
}
我无法理解的是,当我在日志列表中看到被添加到我的 ans 时,为什么我的 ans 是空的。我是不是在犯一些愚蠢的错误。请帮我解决这个问题。如果可能,请帮助我提供链接以了解该问题以及将来如何避免这些问题。
【问题讨论】:
-
每次您向
positions添加一个项目时,您也会删除一个项目,因此它最终为空,正如您的 println 所示。
标签: java algorithm pass-by-reference backtracking pass-by-value