Ways to place K bishops on an NÃ — N chessboard so that no two attack | returns the number of squares in diagonal i ; returns the number of ways to fill a n * n chessboard with k bishops so that no two bishops attack each other . ; return 0 if the number of valid places to be filled is less than the number of bishops ; dp table to store the values ; Setting the base conditions ; calculate the required number of ways ; stores the answer ; Driver code
function squares ( i ) { if ( ( i & 1 ) == 1 ) return parseInt ( i / 4 , 10 ) * 2 + 1 ; else return parseInt ( ( i - 1 ) / 4 , 10 ) * 2 + 2 ; } function bishop_placements ( n , k ) { if ( k > 2 * n - 1 ) return 0 ; let dp = new Array ( n * 2 ) ; for ( let i = 0 ; i < n * 2 ; i ++ ) { dp [ i ] = new Array ( k + 1 ) ; for ( let j = 0 ; j < k + 1 ; j ++ ) { dp [ i ] [ j ] = 0 ; } dp [ i ] [ 0 ] = 1 ; } dp [ 1 ] [ 1 ] = 1 ; for ( let i = 2 ; i < n * 2 ; i ++ ) { for ( let j = 1 ; j <= k ; j ++ ) dp [ i ] [ j ] = dp [ i - 2 ] [ j ] + dp [ i - 2 ] [ j - 1 ] * ( squares ( i ) - j + 1 ) ; } let ans = 0 ; for ( let i = 0 ; i <= k ; i ++ ) { ans += dp [ n * 2 - 1 ] [ i ] * dp [ n * 2 - 2 ] [ k - i ] ; } return ans ; } let n = 2 ; let k = 2 ; let ans = bishop_placements ( n , k ) ; document . write ( ans ) ;