边工作边刷题:70天一遍leetcode: day 97

Bomb Enemy

要点:

  • 什么题?目标是合适的地方摆1个炸弹优化最大攻击怪物数,
    • 为什么这个目标和横竖统计有关(内在关联是什么?):炸弹的特性:分段,某个点和某段内的前后方向都有关联。所以统计段内怪物数
    • 处理的方向是逐行遍历matrix,所以”预处理"可以同时进行:在某段的左边界做,之后其他同段点可以共享。边界条件即初始i==0 or i-1为障碍,终止i为右边界 or i+1为障碍
  • (optional) http://pastebin.com/1MudDima google走迷宫(进一步理解)
    • 类似题,但是要分开预处理neighbors:因为不是逐行扫描做选择,而是路径根据初始点四个方向做dfs

https://repl.it/C9uI/2

class Solution(object):
    def maxKilledEnemies(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        m=len(grid)
        if m==0: return 0
        n=len(grid[0])
        rowcount, colcounts= 0, [0]*n
        maxCount = 0
        for i in xrange(m):
            for j in xrange(n):
                if j==0 or grid[i][j-1]=='W':
                    rowcount, k = 0, j
                    while k<n and grid[i][k]!='W':
                        rowcount+=(grid[i][k]=='E')
                        k+=1
                    
                if i==0 or grid[i-1][j]=='W':
                    colcounts[j], k = 0, i
                    while k<m and grid[k][j]!='W':
                        colcounts[j]+=(grid[k][j]=='E')
                        k+=1

                if grid[i][j]=='0':
                    maxCount = max(maxCount, rowcount+colcounts[j])
            
        return maxCount

sol = Solution()
assert sol.maxKilledEnemies(["0E00","E0WE","0E00"])==3, "max killed is 3"

posted @ 2016-07-07 20:45  absolute100  阅读(97)  评论(0编辑  收藏  举报