码迷,mamicode.com
首页 > 其他好文 > 详细

361. Bomb Enemy

时间:2018-11-29 10:55:31      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:return   not   led   rom   ret   ++   i++   matrix   max   

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: You can only put the bomb at an empty cell.
Example:
Input: [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
Output: 3 
Explanation: For the given grid,

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

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




Walk through the matrix. At the start of each non-wall-streak (row-wise or column-wise), count the number of hits in that streak and remember it. O(mn) time, O(n) space.

int maxKilledEnemies(vector<vector<char>>& grid) {
    int m = grid.size(), n = m ? grid[0].size() : 0;
    int result = 0, rowhits, colhits[n];
    for (int i=0; i<m; i++) {
        for (int j=0; j<n; j++) {
            if (!j || grid[i][j-1] == ‘W‘) {
                rowhits = 0;
                for (int k=j; k<n && grid[i][k] != ‘W‘; k++)
                    rowhits += grid[i][k] == ‘E‘;
            }
            if (!i || grid[i-1][j] == ‘W‘) {
                colhits[j] = 0;
                for (int k=i; k<m && grid[k][j] != ‘W‘; k++)
                    colhits[j] += grid[k][j] == ‘E‘;
            }
            if (grid[i][j] == ‘0‘)
                result = max(result, rowhits + colhits[j]);
        }
    }
    return result;
}

 

361. Bomb Enemy

标签:return   not   led   rom   ret   ++   i++   matrix   max   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/10036115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!