VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-cells-queen-can-move-obstacles-chessborad/

⇱ Number of cells a queen can move with obstacles on the chessboard - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of cells a queen can move with obstacles on the chessboard

Last Updated : 15 Sep, 2023

Consider a N X N chessboard with a Queen and K obstacles. The Queen cannot pass through obstacles. Given the position (x, y) of Queen, the task is to find the number of cells the queen can move.

Examples: 

Input : N = 8, x = 4, y = 4, 
 K = 0
Output : 27

👁 Image

Input : N = 8, x = 4, y = 4, 
 K = 1, kx1 = 3, ky1 = 5
Output : 24

👁 Image

Method 1: 

The idea is to iterate over the cells the queen can attack and stop until there is an obstacle or end of the board. To do that, we need to iterate horizontally, vertically and diagonally. The moves from position (x, y) can be: 

(x+1, y): one step horizontal move to the right. 
(x-1, y): one step horizontal move to the left. 
(x+1, y+1): one step diagonal move up-right. 
(x-1, y-1): one step diagonal move down-left. 
(x-1, y+1): one step diagonal move left-up. 
(x+1, y-1): one step diagonal move right-down. 
(x, y+1): one step downward. 
(x, y-1): one step upward.

Below is C++ implementation of this approach:  


Output
24

Time Complexity: O(n2)
Auxiliary Space: O(n)


 Method 2: 
The idea is to iterate over the obstacles and for those who are in the queen's path, we calculate the free cells upto that obstacle. If there is no obstacle in the path we have to calculate the number of free cells upto end of board in that direction. 

For any (x1, y1) and (x2, y2): 

  • If they are horizontally at same level: abs(x1 - x2 - 1)
  • If they are vertically at same level: abs(y1 - y2 - 1) is the number of free cells between.
  • If they are diagonal: both abs(x1 - x2 - 1) or abs(y1 - y2 - 1) is the number of free cells between.

Below is the implementation of this approach:  

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

Comment
Article Tags: