I'm trying to learn bactracking however, while I would like to add all solution to my arraylist, it only contains the first solution that my method found. I checked isSafe method, it is correct. the only problem is my queensList method. could you please explain how can I add all solution to my arraylist. For instance, for the 4x4 table, my ArrayList's element is that
[0, 1, 0, 0]
[0, 0, 0, 1]
[1, 0, 0, 0]
[0, 0, 1, 0]
public static boolean queensList(int[][] aList, int r, int k, ArrayList<int[][]> qL) {
if (r >= k) {
qL.add(aList);
return true;
}
for (int i = 0; i < k; i++) {
if (isSafe(aList, r, i)) {
aList[r][i] = 1;
if (queensList(aList, r + 1, k, qL))
return true;
aList[r][i] = 0;
}
}
return false;
}
public static boolean isSafe(int[][] trying, int r, int c) {
for (int i = 0; i < trying.length; i++) {
if (trying[r][i] == 1 || trying[i][c] == 1)
return false;
}
int i = 0;
while (r - i < trying.length && 0 <= r - i && c - i < trying.length && 0 <= c - i || r - i < trying.length && 0 <= r - i && c + i < trying.length && 0 <= c + i
|| r + i < trying.length && 0 <= r + i && c - i < trying.length && 0 <= c - i || r + i < trying.length && 0 <= r + i && c + i < trying.length && 0 <= c + i) {
if (r - i < trying.length && 0 <= r - i && c - i < trying.length && 0 <= c - i && trying[r - i][c - i] == 1)
return false;
if (r - i < trying.length && 0 <= r - i && c + i < trying.length && 0 <= c + i && trying[r - i][c + i] == 1)
return false;
if (r + i < trying.length && 0 <= r + i && c - i < trying.length && 0 <= c - i && trying[r + i][c - i] == 1)
return false;
if (r + i < trying.length && 0 <= r + i && c + i < trying.length && 0 <= c + i && trying[r + i][c + i] == 1)
return false;
i++;
}
return true;
}