Concise Python Solution


  • 0
    Y
        def maxKilledEnemies(self, grid):
            offsets = [[[0, -1], [0, 1]], [[-1, 0], [1, 0]]] # Horizontal and vertical.
            memo = [[[-1, -1] for _ in range(len(grid[0]))] for _ in range(len(grid))]
            best = 0
            for index in [0, 1]:
                for row in range(len(grid)):
                    for col in range(len(grid[0])):
                        if grid[row][col] != "0": continue
                        count = 0; finished = False
                        for offset in offsets[index]:
                            new_row, new_col = row + offset[0], col+offset[1]
                            while 0 <= new_col < len(grid[0]) and \
                                  0 <= new_row < len(grid) and grid[new_row][new_col] != "W": 
                                if grid[new_row][new_col] == "E":
                                    count += 1
                                if grid[new_row][new_col] == "0" and memo[new_row][new_col][index] != -1:
                                    count = memo[new_row][new_col][index] 
                                    finished = True; break
                                new_row += offset[0]; new_col += offset[1]
                            if finished: break
                        memo[row][col][index] = count
                        current_total = sum(memo[row][col])
                        best = max(best, current_total)
            return best
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.