2

The puzzle:

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

Here's the code:

public class Solution {
    public int totalNQueens(int n) {
        boolean[][] board = new boolean[n][n];
        return totalNQueens(board, 0, n);
    }
    
    private int totalNQueens(boolean[][] board, int cur, int n) {
        int res = 0;
        if(cur == n) {
            return 1;
        }
        for(int i = 0; i < n; i++) {
            if(!board[cur][i]) {
                boolean[][] subboard = board.clone();
                for(int r = cur + 1; r < n; r++) {
                    subboard[r][i] = true;
                }
                for(int r = cur + 1, c = i - 1; r < n && c >= 0; r++, c--) {
                    subboard[r][c] = true;
                }
                for(int r = cur + 1, c = i + 1; r < n && c < n; r++, c++) {
                    subboard[r][c] = true;
                }
                res += totalNQueens(subboard, cur+1, n);
            }
        }
        return res;
    }
}

The result:

Input:

4

Output:

0

Expected:

2

I can't figure out what's wrong with this code, so please help me, thx in advance.

Community
  • 1
  • 1
user2916610
  • 765
  • 1
  • 5
  • 12

1 Answers1

2

The problem is with this line:

boolean[][] subboard = board.clone();

Java does not have multi-dimensional arrays. So board is actually a one dimensional array of arrays of booleans. The clone only clones the top level array but not the subarrays. So board[0] is actually the same object as subboard[0] and changes made there are never undone.

Henry
  • 42,982
  • 7
  • 68
  • 84