Count Knights that can attack a given pawn in an N * N board | C ++ program to implement the above approach ; Function to count the knights that are attacking the pawn in an M * M board ; Stores count of knights that are attacking the pawn ; Traverse the knights [ ] [ ] array ; Stores absolute difference of X co - ordinate of i - th knight and pawn ; Stores absolute difference of Y co - ordinate of i - th knight and pawn ; If X is 1 and Y is 2 or X is 2 and Y is 1 ; Update cntKnights ; Driver Code ; Stores total count of knights
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntKnightsAttackPawn ( int knights [ ] [ 2 ] , int pawn [ ] , int M ) { int cntKnights = 0 ; for ( int i = 0 ; i < M ; i ++ ) { int X = abs ( knights [ i ] [ 0 ] - pawn [ 0 ] ) ; int Y = abs ( knights [ i ] [ 1 ] - pawn [ 1 ] ) ; if ( ( X == 1 && Y == 2 ) || ( X == 2 && Y == 1 ) ) { cntKnights ++ ; } } return cntKnights ; } int main ( ) { int knights [ ] [ 2 ] = { { 0 , 4 } , { 4 , 5 } , { 1 , 4 } , { 3 , 1 } } ; int pawn [ ] = { 2 , 3 } ; int M = sizeof ( knights ) / sizeof ( knights [ 0 ] ) ; cout << cntKnightsAttackPawn ( knights , pawn , M ) ; return 0 ; }