原题链接在这里:
题目:
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.
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