Given two integers N and K, the task is to find the number of ways to place K bishops on an N × N chessboard so that no two bishops attack each other.
Here is an example for a 5×5 chessboard.
Input: N = 2, K = 2
The different ways to place 2 bishops in a 2 * 2 chessboard are :
Input: N = 4, K = 3
Approach: This problem can be solved using dynamic programming.
- Let dp[i][j] denote the number of ways to place j bishops on diagonals with indices up to i which have the same color as diagonal i. Then i = 1…2N-1 and j = 0…K.
- We can calculate dp[i][j] using only values of dp[i-2] (we subtract 2 because we only consider diagonals of the same color as i). There are two ways to get dp[i][j]. Either we place all j bishops on previous diagonals: then there are dp[i-2][j] ways to achieve this. Or we place one bishop on diagonal i and j-1 bishops on previous diagonals. The number of ways to do this equals the number of squares in diagonal i – (j – 1), because each of j-1 bishops placed on previous diagonals will block one square on the current diagonal.
- The base case is simple: dp[i] = 1, dp = 1.
- Once we have calculated all values of dp[i][j], the answer can be obtained as follows: consider all possible numbers of bishops placed on black diagonals i=0…K, with corresponding numbers of bishops on white diagonals K-i. The bishops placed on black and white diagonals never attack each other, so the placements can be done independently. The index of the last black diagonal is 2N-1, the last white one is 2N-2. For each i we add dp[2N-1][i] * dp[2N-2][K-i] to the answer.
Below is the implementation of the above approach:
- Place K-knights such that they do not attack each other
- Sybil Attack
- Buffer Overflow Attack with Example
- Perform DDoS attack using Torshammer
- Draw a Chessboard in Java Applet
- Probability of Knight to remain in the chessboard
- Range and Update Query for Chessboard Pieces
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- How to place two div side-by-side of the same height using CSS?
- Count number of ways to get Odd Sum
- All ways to add parenthesis for evaluation
- Count of different ways to express N as the sum of 1, 3 and 4
- Number of ways to pair people
- 10 Ways to Create a Stream in Java
- Number of ways to reach the end of matrix with non-zero AND value
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.