Backtracking solution using JAVA. Easy to understand.


  • 0
    S
    public class Solution {
        public List<List<String>> solveNQueens(int n) {
            List<List<String>> result = new ArrayList<>();
            Integer[] columns = new Integer[n];
            ArrayList<Integer[]> res = new ArrayList<>();
            placeQueens(0, columns, res, n);
            for(Integer[] arr : res)
            {
                List<String> list = new ArrayList<>();
                for(int i = 0; i < arr.length; i++)
                {
                    StringBuilder sb = new StringBuilder();
                    int val = arr[i];
                    for(int j = 0; j < val; j++) sb.append(".");
                    sb.append("Q");
                    for(int j = val+1; j < n; j++) sb.append(".");
                    list.add(sb.toString());
                }
                result.add(list);
            }
            return result;
        }
        
        public void placeQueens(int row, Integer[] columns, ArrayList<Integer[]> res, int n)
        {
            if(row == n) res.add(columns.clone());
            else
            {
                for(int col = 0; col < n; col++)
                {
                    if(isValidPlacement(columns, row, col))
                    {
                        columns[row] = col;
                        placeQueens(row+1, columns, res, n);
                    }
                }
            }
        }
        
        public boolean isValidPlacement(Integer[] columns, int row1, int col1)
        {
            for(int row2 = 0; row2 < row1; row2++)
            {
                int col2 = columns[row2];
                if(col1 == col2) return false;
                if(row1 - row2 == Math.abs(col1 - col2)) return false;
            }
            
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.