Cuente los caballos que pueden atacar a un peón dado en un tablero N * N

Dada una array 2D caballeros[][] de tamaño N * 2 , con cada fila de la forma {X, Y} representando las coordenadas de los caballeros , y una array peón[] representando las coordenadas de un peón en un tablero de N * N , la tarea es encontrar la cuenta de caballos presentes en el tablero que está atacando al peón.

Ejemplos:

Entrada: caballeros[][] = { { 0, 4 }, { 4, 5 }, { 1, 4 }, { 3, 1 } }, peón[] = { 2, 3 } 
Salida:
Explicación: 
Los caballos presentes en la coordenada { { 0, 4 }, { 3, 1 } } están atacando el peón. 
Por lo tanto, la salida requerida es 2.

Entrada: caballeros[][] = { { 4, 6 }, { 7, 5 }, { 5, 5 } }, peón[] = { 6, 7 } 
Salida:
Explicación: 
Los caballos presentes en la coordenada { { 4 , 6 }, { 7, 5 }, { 5, 5 } } están atacando el peón. 
Por lo tanto, la salida requerida es 3.

Enfoque: siga los pasos que se indican a continuación para resolver el problema

  • Inicialice una variable, digamos cntKnights , para almacenar el recuento de caballos que atacan al peón.
  • Atraviese la array de caballeros[][] usando la variable i y para cada elemento de la array caballeros[i] , verifique si la array { (caballeros[i][0] – peón[0]), (caballeros[i][1] – peón[1]) } es igual a { 1, 2 } o { 2, 1 } o no. Si se determina que es cierto, incremente el valor de cntKnights en 1 .
  • Finalmente, imprima el valor de cntKnights .

A continuación se muestra la implementación del enfoque anterior:

C++

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

Java

// Java program to implement
// the above approach
import java.io.*;
import java.lang.Math;
 
class GFG{
 
// Function to count the knights that are
// attacking the pawn in an M * M board
static int cntKnightsAttackPawn(int knights[][],
                                int pawn[], int M)
{
     
    // Stores count of knights that
    // are attacking the pawn
    int cntKnights = 0;
     
     // Traverse the knights[][] array
    for(int i = 0; i < M; i++)
    {
         
        // Stores absolute difference of X
        // co-ordinate of i-th knight and pawn
        int X = Math.abs(knights[i][0] - pawn[0]);
     
        // Stores absolute difference of Y
        // co-ordinate of i-th knight and pawn
        int Y = Math.abs(knights[i][1] - pawn[1]);
     
        // If X is 1 and Y is 2 or
        // X is 2 and Y is 1
        if ((X == 1 && Y == 2) ||
            (X == 2 && Y == 1))
        {
             
            // Update cntKnights
            cntKnights++;
        }
    }
    return cntKnights;
}
 
// Driver code
public static void main(String[] args)
{
    int[][] knights = { { 0, 4 }, { 4, 5 },
                        { 1, 4 }, { 3, 1 } };
     
    int[] pawn = new int[]{2, 3};
   
    // Stores total count of knights
    int M = knights.length;
     
    System.out.println(cntKnightsAttackPawn(
        knights, pawn, M));
}
}
 
// This code is contributed by vandanakillari54935

Python3

# Python program to implement
# the above approach
 
# Function to count the knights that are
# attacking the pawn in an M * M board
def cntKnightsAttackPawn(knights, pawn, M):
   
    # Stores count of knights that
    # are attacking the pawn
    cntKnights = 0;
 
    # Traverse the knights array
    for i in range(M):
 
        # Stores absolute difference of X
        # co-ordinate of i-th knight and pawn
        X = abs(knights[i][0] - pawn[0]);
 
        # Stores absolute difference of Y
        # co-ordinate of i-th knight and pawn
        Y = abs(knights[i][1] - pawn[1]);
 
        # If X is 1 and Y is 2 or
        # X is 2 and Y is 1
        if ((X == 1 and Y == 2) or (X == 2 and Y == 1)):
           
            # Update cntKnights
            cntKnights += 1;
 
    return cntKnights;
 
# Driver code
if __name__ == '__main__':
    knights = [[0, 4], [4, 5], [1, 4], [3, 1]];
 
    pawn = [2, 3];
 
    # Stores total count of knights
    M = len(knights);
 
    print(cntKnightsAttackPawn(knights, pawn, M));
 
# This code is contributed by Amit Katiyar

C#

// C# program to implement
// the above approach
using System;
class GFG
{
 
  // Function to count the knights that are
  // attacking the pawn in an M * M board
  static int cntKnightsAttackPawn(int[,] knights, int[] pawn, int M)
  {
    // Stores count of knights that
    // are attacking the pawn
    int cntKnights = 0;
 
    // Traverse the knights[][] array
    for (int i = 0; i < M; i++) {
 
      // Stores absolute difference of X
      // co-ordinate of i-th knight and pawn
      int X = Math.Abs(knights[i, 0] - pawn[0]);
 
      // Stores absolute difference of Y
      // co-ordinate of i-th knight and pawn
      int Y = Math.Abs(knights[i, 1] - pawn[1]);
 
      // If X is 1 and Y is 2 or
      // X is 2 and Y is 1
      if ((X == 1 && Y == 2)
          || (X == 2 && Y == 1)) {
 
        // Update cntKnights
        cntKnights++;
      }
    }
 
    return cntKnights;
  }
 
  // Driver code
  static void Main()
  {
    int[,] knights = {{ 0, 4 }, { 4, 5 }, { 1, 4 }, { 3, 1 }};
 
    int[] pawn = {2, 3};
 
    // Stores total count of knights
    int M = knights.GetLength(0);
 
    Console.WriteLine(cntKnightsAttackPawn(knights, pawn, M));
  }
}
 
// This code is contributed by divyeshrabadiya07

Javascript

<script>
 
// javascript program for the above approach
 
// Function to count the knights that are
// attacking the pawn in an M * M board
function cntKnightsAttackPawn(knights,
                                pawn, M)
{
     
    // Stores count of knights that
    // are attacking the pawn
    let cntKnights = 0;
     
     // Traverse the knights[][] array
    for(let i = 0; i < M; i++)
    {
         
        // Stores absolute difference of X
        // co-ordinate of i-th knight and pawn
        let X = Math.abs(knights[i][0] - pawn[0]);
     
        // Stores absolute difference of Y
        // co-ordinate of i-th knight and pawn
        let Y = Math.abs(knights[i][1] - pawn[1]);
     
        // If X is 1 and Y is 2 or
        // X is 2 and Y is 1
        if ((X == 1 && Y == 2) ||
            (X == 2 && Y == 1))
        {
             
            // Update cntKnights
            cntKnights++;
        }
    }
    return cntKnights;
}
 
// Driver Code
     
        let knights = [[ 0, 4 ], [ 4, 5 ],
                        [ 1, 4 ], [ 3, 1 ]];
     
    let pawn = [2, 3];
   
    // Stores total count of knights
    let M = knights.length;
     
    document.write(cntKnightsAttackPawn(
        knights, pawn, M));
 
</script>
Producción

2

Complejidad de tiempo: O(M), donde M es el número total de conteo de caballeros  
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por nitishkumar199703 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *