VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-knights-that-can-attack-a-given-pawn-in-an-n-n-board/

⇱ Count Knights that can attack a given pawn in an N * N board - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Knights that can attack a given pawn in an N * N board

Last Updated : 3 Oct, 2025

Given a 2D array knights[][] of size N * 2, with each row of the form { X, Y } representing the coordinates of knights, and an array pawn[] representing the coordinates of a pawn in an N * N board, the task is to find the count of knights present in the board that is attacking the pawn.

Examples:

Input: knights[][] = { { 0, 4 }, { 4, 5 }, { 1, 4 }, { 3, 1 } }, pawn[] = { 2, 3 } 
Output:
Explanation: 
The knights present at coordinate { { 0, 4 }, { 3, 1 } } are attacking the pawn. 
Therefore, the required output is 2.

Input: knights[][] = { { 4, 6 }, { 7, 5 }, { 5, 5 } }, pawn[] = { 6, 7 } 
Output:
Explanation: 
The knights present at coordinate { { 4, 6 }, { 7, 5 }, { 5, 5 } } are attacking the pawn. 
Therefore, the required output is 3.

Approach: Follow the steps given below to solve the problem

  • Initialize a variable, say cntKnights, to store the count of knights that are attacking the pawn.
  • Traverse the knights[][] array using variable i and for every array element knights[i], check if the array { (knights[i][0] - pawn[0]), (knights[i][1] - pawn[1]) } is equal to either { 1, 2 } or { 2, 1 } or not. If found to be true, then increment the value of cntKnights by 1.
  • Finally, print the value of cntKnights.

Below is the implementation of the above approach:


Output
2

Time Complexity: O(M), where M is the total count number of knights 
Auxiliary Space: O(1)

Comment