Wednesday, August 2, 2017

361. Bomb Enemy

Given a 2D grid, each cell is either a wall 'Y', an enemy 'X' or empty '0' (the number zero), return the maximum enemies you can kill using 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.
Note that you can only put the bomb at an empty cell.
Example:
For the given grid

0 w 0 0
e 0 e w
0 w 0 e

return 3. (Placing a bomb at (1,1) kills 3 enemies)



using DP:

DP with the same size of matrix mat;

each element is a pair (row, col), row means the sum of enimy in current row based on current position, col means the sum of enimy of column;

fill the DP one by one from left to right, when meet 'e', copy related value; meet 0, using DP or process; meet wall pass.

For the given mat

0 w 0 0
e 0 e w
0 w 0 e
build dp, with '-1' mean not applicable
(-1,-1) (-1,-1) (-1,-1) (-1,-1) 
(-1,-1) (-1,-1) (-1,-1) (-1,-1) 
(-1,-1) (-1,-1) (-1,-1) (-1,-1)
calculation: 
(0,0) (-1,-1) (0, 1) (0, 0) ........


No comments:

Post a Comment