your exit condition of your function queensList
should be only when (r >= k)
, which means when the row r
comes to the end k
, and the queen is still safe, that's a valid solution.
However in your implementation, you also returned when you find a solution in the for loop, which means it did not finish the whole for
loop to find all the possible solutions.
so make a small change to your backtracking function like this:
public static void queensList(int[][] aList, int r, int k, ArrayList<int[][]> qL) {
//exit condition
if (r >= k) {
qL.add(aList);
return;
}
for (int i = 0; i < k; i++) {
if (isSafe(aList, r, i)) {
aList[r][i] = 1;
queensList(aList, r + 1, k, qL);
aList[r][i] = 0;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…