VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-cells-attacked-by-rook-or-bishop-in-given-chessboard/

⇱ Maximum cells attacked by Rook or Bishop in given Chessboard - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum cells attacked by Rook or Bishop in given Chessboard

Last Updated : 31 May, 2022

Given three integers N, R, and C representing an N*N chessboard and the position (R, C) where the rook and the bishop is placed. The task is to find out who can attack the most number of cells (except the cell they are in) and how many.

Note: 

  • A rook can move only horizontally along the row or vertically along the column and any number of cells at a time
  • A bishop can move diagonally any number of cells at a time.

Examples:

Input: N = 3, R = 2, C = 1
Output: Rook, 4
Explanation: Rook can attack 2 cells in the row and 2 cells along the column. So 2+2 = 4.
Bishop can attack only 2 cells (1, 2) and (3, 2).

Input: N=1, R=1, C=1
Output: Both, 0

Approach: The problem can be solved by the following observation:

A rook can move vertically upwards or downwards and horizontally to the left or to the right. 
So total cells attacked by rook = (N - 1) + (N - 1) = 2*(N - 1)

A bishop can attack only diagonally i.e., across the primary diagonal or the secondary diagonal.
So total number of cells attacked along the main diagonal is min(R-1, C-1) + min(N-R, N-C).
Total number of cells attacked along the secondary diagonal is min(R-1, N-C) + min(N-R, C-1)

Follow the steps below to solve the problem:

  • Find the total cells under attack by the rook (say X) using the above formula.
  • Find the total cells under attack by the bishop (say Y) using the above formula.
  • Check which one is greater and return the answer accordingly.

Below is the implementation of the above approach:


Output
Rook, 4

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

Comment