VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-any-king-is-unsafe-on-the-chessboard-or-not/

⇱ Check if any King is unsafe on the Chessboard or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if any King is unsafe on the Chessboard or not

Last Updated : 18 Oct, 2021

Given a matrix board[][] consisting of the characters K or k, Q or q, B or b, N or n, R or r, and P or p (Upper case white and lower case black) representing the King, the Queen, the Bishop, the Knight, the Rook, and Pawns of Black and White color respectively, and empty spaces indicated by '-', the task is to check which king (black of white) is unsafe, i.e. if it is under attack (can be eliminated) by any of the other pieces and print the answer accordingly. 
Note: If both kings are safe then output "No King in danger".
Examples: 

Input: 
board[][] = {{- - - k - - - -}, 
 {p p p - p p p p}, 
 {- - - - - b - -}, 
 {- - - R - - - -}, 
 {- - - - - - - -}, 
 {- - - - - - - -}, 
 {P - P P P P P P}, 
 {K - - - - - - - }}
Output:White King in danger
Explanation: Black bishop can attack the white king.

Input:
board[][] = {{- - k - - - - -}, 
 {p p p - p p p p}, 
 {- - - - - - b -}, 
 {- - - R - - - -}, 
 {- - - - - - - -}, 
 {- - - - - - - -}
 {P - P P P P P P}, 
 {K - - - - - - -}}
Output: No King in danger

Approach: 
The approach is to check the moves of each and every piece on the chessboard:  

  1. Check for the position of both white and black kings.
  2. For each king, check Rook, bishops, knight, king, Queen, Pawn of the opposite color, whether they are attacking the king or not.
  3. Checking for attack by the queen is a combination of checking attacks by rooks and bishops. If any of the conditions are true then the queen will attack.
  4. If none of the attack conditions are satisfied for any of the two kings, then there is no danger to both the king.
  5. Otherwise, print the answer for the king whose unsafe condition is satisfied.

Below is the implementation of this approach.

 
 


Output: 
White king in danger

 

Time Complexity: O(N3
Auxiliary Space: O(1)

Comment