Similar Problems

Similar Problems not available

Bomb Enemy - Leetcode Solution

Companies:

LeetCode:  Bomb Enemy Leetcode Solution

Difficulty: Medium

Topics: matrix dynamic-programming array  

Problem Statement: You are given a 2D grid of size m x n, where each cell is either empty (0) or blocked by a wall (1). You are also given n bombs. Each bomb can be placed in the empty cell, but once it is placed, it will explode and destroy all the walls in the same row and column as the bomb. Each bomb can only be used once. Find the maximum number of walls that can be destroyed.

Example: Input: grid = [ [0,0,0,0,0,0,1], [0,0,0,0,1,0,1], [0,0,0,1,0,0,1], [0,0,0,0,0,1,0], [1,0,0,0,0,0,1], [0,0,0,1,0,0,1], [0,0,1,0,0,0,0], ], bombs = 2 Output: 12

Solution:

  1. Initialize the count to 0, the array to store the number of walls, and another array to store the bomb's coordinates that we choose.

count, walls, bombs = 0, [], []

  1. Iterate over the rows and columns of the grid. The nested loop iterates over the rows of the grid, and the inner loop iterates over the columns of the grid. If the current cell is a wall, then append 0 to the walls array, otherwise, append 1 to the walls array.

for r in range(m): for c in range(n): if grid[r][c] == 1: walls.append(0) else: walls.append(1)

  1. Iterate over the rows and columns of the grid again, this time to find the maximum number of walls that can be destroyed by placing one bomb.

for r in range(m): for c in range(n): if grid[r][c] == 0: bombs.append((r,c)) w = walls[r*n : (r+1)*n] + walls[c::n] count = max(count, sum(w))

  1. Iterate over the coordinates of the chosen bombs and record the maximum number of walls that can be destroyed.

for i in range(len(bombs)): for j in range(i+1, len(bombs)): br, bc = bombs[i] er, ec = bombs[j] if br == er or bc == ec: w = walls[br*n : (br+1)n] + walls[bc::n] + walls[ern : (er+1)*n] + walls[ec::n] count = max(count, sum(w))

  1. Return the count.

return count

Time Complexity: O(m^2*n^2) where m is the number of rows and n is the number of columns.

Space Complexity: O(m*n) to store the walls array and the bombs array.

Overall, the problem can be solved using an exhaustive approach with O(m^2*n^2) time complexity.

Bomb Enemy Solution Code

1