Count Knights that can attack a given pawn in an N * N board | Java 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
import java . io . * ; import java . lang . Math ; class GFG { static int cntKnightsAttackPawn ( int knights [ ] [ ] , int pawn [ ] , int M ) { int cntKnights = 0 ; for ( int i = 0 ; i < M ; i ++ ) { int X = Math . abs ( knights [ i ] [ 0 ] - pawn [ 0 ] ) ; int Y = Math . abs ( knights [ i ] [ 1 ] - pawn [ 1 ] ) ; if ( ( X == 1 && Y == 2 ) || ( X == 2 && Y == 1 ) ) { cntKnights ++ ; } } return cntKnights ; } public static void main ( String [ ] args ) { int [ ] [ ] knights = { { 0 , 4 } , { 4 , 5 } , { 1 , 4 } , { 3 , 1 } } ; int [ ] pawn = new int [ ] { 2 , 3 } ; int M = knights . length ; System . out . println ( cntKnightsAttackPawn ( knights , pawn , M ) ) ; } }