Comprueba si todos los enemigos mueren con bombas colocadas en una array

Dada una array de caracteres como entrada, la tarea es verificar si todos los enemigos mueren o no según las siguientes condiciones: 

1. La array puede contener 3 caracteres 
X –> Denota el área de Guerra. 
B –> Denota la bomba. 
E –> Denota los Enemigos.
2. La bomba ‘B’ puede explotar solo en direcciones horizontales y verticales de un extremo a otro. 
3. Si todos los enemigos son asesinados por las bombas actuales, escriba , de lo contrario escriba No 
 

Ejemplos:  

Input: matrix =
XXEX
XBXX
XEXX
XXBX 
Output: Yes

Input: matrix =
XXEX
XBXX
XEXX
XXXX
Output: No

Enfoque: El problema dado se puede resolver mediante el siguiente enfoque:  

  1. Consigue el personaje Matrix
  2. Traverse para encontrar todos los índices de bombas en la array
  3. Y almacene las filas y la columna en la array rs y cls.
  4. Después de todos los recorridos, verifique para cada enemigo si hay una bomba presente en esa fila o columna o no.
  5. Si algún enemigo está presente en una fila o columna donde no hay bomba, escriba NO, de lo contrario, escriba Sí.

Implementación: 

C++

// C++ program to kill all enemies
 
#include <iostream>
using namespace std;
 
// Function to find Enemies killed or not
int Kill_Enemy(string s[], int row, int col)
{
 
    int rs[row]={0},cls[col]={0};
 
 for(int i=0;i<row;i++){
 
  for(int j=0;j<col;j++){
 
    if(s[i][j]=='B'){
 
        rs[i]++;cls[j]++;
 
       }
 
   }
 
 }
 
 for(int i=0;i<row;i++){
 
  for(int j=0;j<col;j++){
 
    if(s[i][j]=='E'){
 
        if(rs[i]==0&&cls[j]==0)return 0;
 
       }
 
   }
 
 }
 
 return 1;
}
 
// Driver Code
int main(int argc, char** argv)
{
    // Get the input matrix
    string s[] = { "XXEX",
                   "XBXX",
                   "XEXX",
                   "XXBX" };
 
    // Calculate Rows and columns of the string
    int row = sizeof(s) / sizeof(s[0]),
        col = s[0].length();
 
    // Check if all enemies will be killed or not
    if (Kill_Enemy(s, row, col) == 1)
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}

Java

// Java program to kill all enemies
class GFG
{
 
// Function to find Enemies killed or not
static int Kill_Enemy(char [][]s, int row, int col)
{
 
    int i, j, x, y;
 
    // Loop to evaluate the Bomb
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
 
            // Check if this index is a bomb
            if (s[i][j] == 'B')
            {
 
                // Kill all enemies
                // in horizontal direction
                for (x = 0; x < row; x++)
                {
                    if (s[x][j] != 'B')
                        s[x][j] = 'X';
                }
 
                // Kill all enemies
                // in vertical direction
                for (y = 0; y < col; y++)
                {
                    if (s[i][y] != 'B')
                        s[i][y] = 'X';
                }
            }
        }
    }
     
    // All bombs have been found
 
    // Check if any enemy is still present
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
 
            if (s[i][j] == 'E')
 
                // Since an enemy is present
                // Return 0 denoting No as output
                return 0;
        }
    }
 
    // Since all enemies are killed
    // Return 1 denoting Yes as output
    return 1;
}
 
// Driver Code
public static void main(String[] args)
{
    // Get the input matrix
    char [][]s = { "XXEX".toCharArray(),
                "XBXX".toCharArray(),
                "XEXX".toCharArray(),
                "XXBX".toCharArray() };
 
    // Calculate Rows and columns of the String
    int row = s.length,
        col = s[0].length;
 
    // Check if all enemies will be killed or not
    if (Kill_Enemy(s, row, col) == 1)
        System.out.print("Yes");
    else
        System.out.print("No");
}
}
 
// This code is contributed by Rajput-Ji

Python3

# Python3 program to kill all enemies
 
# Function to find Enemies killed or not
def Kill_Enemy(s, row, col):
    i, j, x, y = 0, 0, 0, 0;
 
    # Loop to evaluate the Bomb
    for i in range(row):
        for j in range(col):
             
            # Check if this index is a bomb
            if (s[i][j] == 'B'):
 
                # Kill all enemies
                # in horizontal direction
                for x in range(row):
                    if (s[x][j] != 'B'):
                        s[x][j] = 'X';
 
                # Kill all enemies
                # in vertical direction
                for y in range(col):
                    if (s[i][y] != 'B'):
                        s[i][y] = 'X';
 
    # All bombs have been found
 
    # Check if any enemy is still present
    for i in range(row):
        for j in range(col):
 
            if (s[i][j] == 'E'):
 
                # Since an enemy is present
                # Return 0 denoting No as output
                return 0;
 
    # Since all enemies are killed
    # Return 1 denoting Yes as output
    return 1;
 
# Driver Code
if __name__ == '__main__':
 
    # Get the input matrix
    s = [['X','X','E','X'],
        ['X','B','X','X'],
        ['X','E','X','X'],
        ['X','X','B','X']]
 
    # Calculate Rows and columns of the String
    row = len(s);
    col = len(s[0]);
 
    # Check if all enemies will be killed or not
    if (Kill_Enemy(s, row, col) == 1):
        print("Yes");
    else:
        print("No");
 
# This code is contributed by Rajput-Ji

C#

// C# program to kill all enemies
using System;
 
class GFG
{
 
// Function to find Enemies killed or not
static int Kill_Enemy(char [,]s,
                      int row, int col)
{
    int i, j, x, y;
 
    // Loop to evaluate the Bomb
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
 
            // Check if this index is a bomb
            if (s[i, j] == 'B')
            {
 
                // Kill all enemies
                // in horizontal direction
                for (x = 0; x < row; x++)
                {
                    if (s[x, j] != 'B')
                        s[x, j] = 'X';
                }
 
                // Kill all enemies
                // in vertical direction
                for (y = 0; y < col; y++)
                {
                    if (s[i, y] != 'B')
                        s[i, y] = 'X';
                }
            }
        }
    }
     
    // All bombs have been found
 
    // Check if any enemy is still present
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
 
            if (s[i, j] == 'E')
 
                // Since an enemy is present
                // Return 0 denoting No as output
                return 0;
        }
    }
 
    // Since all enemies are killed
    // Return 1 denoting Yes as output
    return 1;
}
 
// Driver Code
public static void Main(String[] args)
{
    // Get the input matrix
    char [,]s = {{'X', 'B', 'X', 'X'},
                 {'X', 'E', 'X', 'X'},
                 {'X', 'X', 'B', 'X'}};
     
    // Calculate Rows and columns of the String
    int row = s.GetLength(0),
        col = s.GetLength(1);
 
    // Check if all enemies will be killed or not
    if (Kill_Enemy(s, row, col) == 1)
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed by Rajput-Ji

Javascript

<script>
 
    // JavaScript program to kill all enemies
     
    // Function to find Enemies killed or not
    function Kill_Enemy(s, row, col)
    {
 
        let i, j, x, y;
 
        // Loop to evaluate the Bomb
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < col; j++)
            {
 
                // Check if this index is a bomb
                if (s[i][j] == 'B')
                {
 
                    // Kill all enemies
                    // in horizontal direction
                    for (x = 0; x < row; x++)
                    {
                        if (s[x][j] != 'B')
                            s[x][j] = 'X';
                    }
 
                    // Kill all enemies
                    // in vertical direction
                    for (y = 0; y < col; y++)
                    {
                        if (s[i][y] != 'B')
                            s[i][y] = 'X';
                    }
                }
            }
        }
 
        // All bombs have been found
 
        // Check if any enemy is still present
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < col; j++)
            {
 
                if (s[i][j] == 'E')
 
                    // Since an enemy is present
                    // Return 0 denoting No as output
                    return 0;
            }
        }
 
        // Since all enemies are killed
        // Return 1 denoting Yes as output
        return 1;
    }
     
    // Get the input matrix
    let s = [ "XXEX".split(''),
                "XBXX".split(''),
                "XEXX".split(''),
                "XXBX".split('') ];
  
    // Calculate Rows and columns of the String
    let row = s.length, col = s[0].length;
  
    // Check if all enemies will be killed or not
    if (Kill_Enemy(s, row, col) == 1)
        document.write("Yes");
    else
        document.write("No");
   
</script>
Producción: 

Yes

 

Complejidad de tiempo: O(M × N) // donde M es el número de filas y N es el número de columnas
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por VISHAL_PERIYASAMY_R 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 *