Skip to content

Commit b3ee24c

Browse files
committed
Adding solution of Bomb Enemy
1 parent efdd131 commit b3ee24c

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

300-400q/361.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
'''
2+
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.
3+
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.
4+
Note that you can only put the bomb at an empty cell.
5+
6+
Example:
7+
8+
For the given grid
9+
0 E 0 0
10+
E 0 W E
11+
0 E 0 0
12+
return 3. (Placing a bomb at (1,1) kills 3 enemies)
13+
'''
14+
15+
class Solution(object):
16+
def maxKilledEnemies(self, grid):
17+
if not grid or len(grid) == 0 or len(grid[0]) == 0:
18+
return 0
19+
20+
result, row_count = float('-inf'), 0
21+
column_count = [0]*len(grid[0])
22+
for row in range(len(grid)):
23+
for column in range(len(grid[0])):
24+
if column == 0 or grid[row][column-1] == 'W':
25+
row_count = 0
26+
for index in range(column, len(grid[0])):
27+
if grid[row][index] == 'W':
28+
break
29+
row_count += 1 if grid[row][index] == 'E' else 0
30+
31+
if row == 0 or grid[row-1][column] == 'W':
32+
column_count[column] = 0
33+
for index in range(row, len(grid)):
34+
if grid[index][column] == 'W':
35+
break
36+
column_count[column] += 1 if grid[index][column] == 'E' else 0
37+
38+
if grid[row][column] == '0':
39+
result = max(result, row_count + column_count[column])
40+
return result
41+
42+
43+
solution = Solution()
44+
grid = [['0', 'E', '0', '0'],
45+
['E', '0', 'W', 'E'],
46+
['0', 'E', '0', '0']]
47+
print solution.maxKilledEnemies(grid)

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/).
108108
|387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [Python](./300-400q/387.py)|Easy|
109109
|380|[Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [Python](./300-400q/380.py)|Hard|
110110
|378|[Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix) | [Python](./300-400q/378.py)|Medium|
111+
|361|[Bomb Enemy](https://leetcode.com/problems/bomb-enemy)|[Python](./300-400q/361.py)|Medium|
111112
|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [Python](./300-400q/350.py)|Easy|
112113
|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [Python](./300-400q/347.py)|Medium|
113114
|346|[Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream)|[Python](./300-400q/346.py)|Easy|

0 commit comments

Comments
 (0)