Killing Enemy in JavaScript

In JavaScript, we can solve the "killing enemy" problem by finding the optimal position to place a bomb that kills the maximum number of enemies in a 2D grid. The bomb destroys all enemies in the same row and column until it hits a wall.

Problem Statement

Given a 2D grid where each cell is either a wall 'W', an enemy 'E', or empty '0', we need to find the maximum enemies we can kill using only one bomb. The bomb can only be placed in empty cells and kills all enemies in the same row and column until blocked by walls.

Example Input

const arr = [
    ['0', 'E', '0', '0'],
    ['E', '0', 'W', 'E'],
    ['0', 'E', '0', '0']
];
console.log("Input grid:");
console.log(arr);
Input grid:
[
  [ '0', 'E', '0', '0' ],
  [ 'E', '0', 'W', 'E' ],
  [ '0', 'E', '0', '0' ]
]

Solution Approach

The algorithm uses dynamic programming to count enemies in rows and columns efficiently. For each empty cell, it calculates the total enemies that can be killed by placing a bomb there.

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) {
            // Count enemies in current row segment
            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;
                    }
                }
            }
            
            // Count enemies in current column segment
            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;
                    }
                }
            }
            
            // Update maximum if current cell is empty
            if (arr[i][j] === '0' && rows + cols[j] > result) {
                result = rows + cols[j];
            }
        }
    }
    return result;
};

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

console.log("Maximum enemies killed:", killEnemy(arr));
Maximum enemies killed: 3

How It Works

The algorithm processes each cell and:

  • Recalculates row enemy count when hitting a wall or starting a new row
  • Recalculates column enemy count when hitting a wall or starting a new column
  • For empty cells, combines row and column counts to find the maximum

Step-by-Step Example

// Visualizing the optimal bomb placement
const visualizeBombPlacement = (arr) => {
    console.log("Grid analysis:");
    console.log("Position [1,1] (row 1, col 1):");
    console.log("- Row enemies: E at [1,0] = 1 enemy");
    console.log("- Column enemies: E at [0,1] and E at [2,1] = 2 enemies"); 
    console.log("- Total: 1 + 2 = 3 enemies");
    
    // Show the grid with bomb position marked
    const gridCopy = arr.map(row => [...row]);
    gridCopy[1][1] = 'B'; // Mark bomb position
    console.log("\nGrid with bomb at [1,1]:");
    gridCopy.forEach((row, i) => {
        console.log(`Row ${i}: [${row.join(', ')}]`);
    });
};

visualizeBombPlacement(arr);
Grid analysis:
Position [1,1] (row 1, col 1):
- Row enemies: E at [1,0] = 1 enemy
- Column enemies: E at [0,1] and E at [2,1] = 2 enemies
- Total: 1 + 2 = 3 enemies

Grid with bomb at [1,1]:
Row 0: [0, E, 0, 0]
Row 1: [E, B, W, E]
Row 2: [0, E, 0, 0]

Time Complexity

The time complexity is O(m × n × (m + n)) in the worst case, where m is the number of rows and n is the number of columns. However, the dynamic programming approach with memoization makes it efficient for practical use.

Conclusion

This solution efficiently finds the optimal bomb placement by using dynamic programming to count enemies in row and column segments. The algorithm handles walls as barriers and maximizes enemy elimination with a single bomb placement.

Updated on: 2026-03-15T23:19:00+05:30

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements