N Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.

For example, There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

Solution:

public class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> ans = new ArrayList<>();
        List<String> candidateRows = new ArrayList<>();
        String str = "";
        for(int i=0; i<n; i++) str += ".";
        for(int i=0; i<n; i++) candidateRows.add(str.substring(0,i)+'Q'+str.substring(i+1));
        solve(ans, n, candidateRows, new ArrayList<String>());
        return ans;
    }
    public void solve(List<List<String>> ans, int n, List<String> candidateRows, List<String> list){
        /* check validation */
        for(int i=0; i<list.size(); i++){
            for(int j=i+1; j<list.size(); j++){
                if(Math.abs(i-j)==Math.abs(list.get(i).indexOf('Q')-list.get(j).indexOf('Q'))) return;
            }
        }
        
        if(list.size()==n) ans.add(new ArrayList<>(list));
        
        for(int i=0; i<candidateRows.size(); i++){
            String rowStr = candidateRows.get(i);
            list.add(rowStr);
            candidateRows.remove(i);
            solve(ans, n, candidateRows, list);
            candidateRows.add(i, rowStr);
            list.remove(list.size()-1);
        }
    }
}
comments powered by Disqus