Simple backtracking JAVA solution. Easy to understand.


  • 0
    S
    public class Solution {
        public int totalNQueens(int n) {
            Integer[] columns = new Integer[n];
            ArrayList<Integer[]> res = new ArrayList<>();
            placeQueens(0, columns, res, n);
            return res.size();
        }
        
        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.