361.Bomb Enemy

Tags: [matrix], [preprocessing], [memorize], [memo], [start_end], [two_pointer]

Com: {g}

Link: https://leetcode.com/problems/bomb-enemy/\#/description

Given a 2D grid, each cell is either a wall'W', an enemy'E'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 E 0 0
E 0 W E
0 E 0 0

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

Solution: Preprocessing, Memorize

class Solution(object):
    def maxKilledEnemies(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        if not grid or not grid[0]:
            return 0

        num_of_rows = len(grid)
        num_of_cols = len(grid[0])

        enemy_countings = [[0 for _ in xrange(num_of_cols)] for _ in xrange(num_of_rows)]
        for row in xrange(num_of_rows):
            start = 0
            end = 0
            counter = 0
            while end < num_of_cols:
                if grid[row][end] == 'W':
                    for col in xrange(start, end):
                        enemy_countings[row][col] += counter

                    start = end + 1
                    counter = 0
                elif grid[row][end] == 'E':
                    counter += 1

                end += 1

            for col in xrange(start, end):
                enemy_countings[row][col] += counter

        for col in xrange(num_of_cols):
            start = 0
            end = 0
            counter = 0
            while end < num_of_rows:
                if grid[end][col] == 'W':
                    for row in xrange(start, end):
                        enemy_countings[row][col] += counter

                    start = end + 1
                    counter = 0
                elif grid[end][col] == 'E':
                    counter += 1

                end += 1

            for row in xrange(start, end):
                enemy_countings[row][col] += counter

        max_num = 0
        for row in xrange(num_of_rows):
            for col in xrange(num_of_cols):
                if grid[row][col] == '0':
                    max_num = max(max_num, enemy_countings[row][col])

        return max_num

Note:

  • Time complexity = O(n), n is the total number of elements in the given grid.
  • Space complexity = O(n), n is the total number of elements in the given grid.

results matching ""

    No results matching ""