My simple Java Solution


  • 0
    R
    public class Solution {
        private int count;
        public int totalNQueens(int n) {
            if (n <= 0) {
                return count;
            }
            search(n, new ArrayList<Integer>());
            return count;
        }
        
        private void search(int n, List<Integer> cols) {
            if (cols.size() == n) {
                count++;
                return;
            }   
            
            for (int col = 0; col < n; col++) {
                if (!isValid(cols, col)) {
                    continue;
                }
                cols.add(col);
                search (n, cols);
                cols.remove(cols.size() - 1);
            }
        }
        
        private boolean isValid(List<Integer> cols, int col) {
            int row = cols.size();
            for (int i = 0; i < row; i++) {
                // same column
                if (col == cols.get(i)) {
                    return false;
                }
                // left-top to right-bottom
                if (row - i == col - cols.get(i)) {
                    return false;
                }
                // right-top to left-bottom
                if (i - row == col - cols.get(i)) {
                    return false;
                }
            }
            return true;
        }
        
    }

Log in to reply
 

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