博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 361. Bomb Enemy
阅读量:5075 次
发布时间:2019-06-12

本文共 1172 字,大约阅读时间需要 3 分钟。

原题链接在这里:

题目:

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 grid0 E 0 0E 0 W E0 E 0 0return 3. (Placing a bomb at (1,1) kills 3 enemies)

题解:

DP问题. 要储存当前格子所在行和列能看到的敌人个数. 就拿两排array 来计数. 当遇到边界或者墙,就需要重新计算.

用数组colHits储存列的. 因为行的更新和指针是同向移动的,所以用一个number就可以. 

递推时, 在遇到墙和边界时清零重算, 否则敌人数目不变.

起始值都是0. 

Time Complexity: O(m*n). m = grid.length, n = grid[0].length. 每个格子至多走两边.

Space: O(n). 可选m 和n中较小的.

AC Java:

1 class Solution { 2     public int maxKilledEnemies(char[][] grid) { 3         if(grid == null || grid.length == 0 || grid[0].length == 0){ 4             return 0; 5         } 6          7         int m = grid.length; 8         int n = grid[0].length; 9         10         int res = 0;11         int [] colHits = new int[n];12         int rowHits = 0;13         14         for(int i = 0; i

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/7604707.html

你可能感兴趣的文章