北美程序员面试干货

LeetCode 361 [Bomb Enemy]

2016-09-12  本文已影响640人  Jason_Yuan

原题

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.

样例
给出如下矩阵

0 E 0 0
E 0 W E
0 E 0 0

返回3,把炸弹放在(1, 1)可以炸死3个敌人

解题思路

完整代码

class Solution:
    # @param {character[][]} grid Given a 2D grid, each cell is either 'W', 'E' or '0'
    # @return {int} an integer, the maximum enemies you can kill using one bomb
    def maxKilledEnemies(self, grid):
        # Write your code here
        m, n = len(grid), 0
        if m:
            n = len(grid[0])
        
        res, rows = 0, 0
        cols = [0 for i in range(n)]
        
        for i in range(m):
            for j in range(n):
                if j == 0 or grid[i][j - 1] == "W":
                    rows = 0
                    for k in range(j, n):
                        if grid[i][k] == "W":
                            break
                        if grid[i][k] == "E":
                            rows += 1
                        
                if i == 0 or grid[i - 1][j] == "W":
                    cols[j] = 0
                    for k in range(i, m):
                        if grid[k][j] == "W":
                            break
                        if grid[k][j] == "E":
                            cols[j] += 1
                
                if grid[i][j] == "0" and rows + cols[j] > res:
                    res = rows + cols[j]
        
        return res
上一篇 下一篇

猜你喜欢

热点阅读