Intuitive Java Solution


  • 0
    J
        
        public int totalNQueens(int n) {
            if(n <= 0)
                return count;
            solver(new int[n][n], 0);
            return count;
        }
        
        public void solver(int[][] board, int row) {
            if(row == board.length) {
                count++;
                return;
            }
            for(int j = 0; j < board[0].length; j++) {
                // if this is a valid position for placing a queen
                if(validPos(board, row, j)) {
                    // place queen here
                    board[row][j] = 1;
                    // recurse down
                    solver(board, row + 1);
                    board[row][j] = 0;
                }
            }
        }
        
        public boolean validPos(int[][] board, int row, int col) {
            // check if previous columns contains queen
            for(int i = row - 1; i >= 0; i--) {
                if(board[i][col] != 0) return false;
            }
            // check if previous diagonal contains queen
            for(int i = row - 1, j = col + 1; i >= 0 && j < board.length; i--, j++) {
                if(board[i][j] != 0) return false;
            }
            // check if previous diagonal contains queen
            for(int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
                if(board[i][j] != 0) return false;
            }
            
            return true;
        }

Log in to reply
 

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