Killing Enemy in JavaScript


Problem

Suppose, we have a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero). We are required to write a function that returns the maximum enemies we can kill using only one bomb.

The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed.

We also have to keep in mind that we can only put the bomb in an empty cell. For example, if the input to the function is −

const arr = [
   ['0', 'E', '0', '0'],
   ['E', '0', 'W', 'E'],
   ['0', 'E', '0', '0']
];

Then the output should be −

const output = 3;

Output Explanation:

Placing a bomb at [1,1] will kill 3 enemies which is the highest.

Example

The code for this will be −

 Live Demo

const arr = [
   ['0', 'E', '0', '0'],
   ['E', '0', 'W', 'E'],
   ['0', 'E', '0', '0']
];
const killEnemy = (arr = []) => {
   let m = arr.length;
   let n = m > 0 ? arr[0].length : 0;
   let result = 0, rows = 0;
   const cols = [];
   for (let i = 0; i < m; ++i) {
      for (let j = 0; j < n; ++j) {
         if (j === 0 || arr[i][j-1] === 'W') {
            rows = 0;
            for (let k = j; k < n && arr[i][k] != 'W'; ++k)
            if (arr[i][k] === 'E')
            rows += 1;
         }
         if (i === 0 || arr[i-1][j] === 'W') {
            cols[j] = 0;
            for (let k = i; k < m && arr[k][j] != 'W'; ++k)
               if (arr[k][j] === 'E')
                  cols[j] += 1;
         }
         if (arr[i][j] === '0' && rows + cols[j] > result)
         result = rows + cols[j];
      }
   }
   return result;
};
console.log(killEnemy(arr));

Output

And the output in the console will be −

3

Updated on: 18-Mar-2021

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements