Skip to content

Commit

Permalink
Adding solution of Bomb Enemy
Browse files Browse the repository at this point in the history
  • Loading branch information
Garvit244 committed Jun 3, 2019
1 parent efdd131 commit b3ee24c
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
47 changes: 47 additions & 0 deletions 300-400q/361.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
'''
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 grid
0 E 0 0
E 0 W E
0 E 0 0
return 3. (Placing a bomb at (1,1) kills 3 enemies)
'''

class Solution(object):
def maxKilledEnemies(self, grid):
if not grid or len(grid) == 0 or len(grid[0]) == 0:
return 0

result, row_count = float('-inf'), 0
column_count = [0]*len(grid[0])
for row in range(len(grid)):
for column in range(len(grid[0])):
if column == 0 or grid[row][column-1] == 'W':
row_count = 0
for index in range(column, len(grid[0])):
if grid[row][index] == 'W':
break
row_count += 1 if grid[row][index] == 'E' else 0

if row == 0 or grid[row-1][column] == 'W':
column_count[column] = 0
for index in range(row, len(grid)):
if grid[index][column] == 'W':
break
column_count[column] += 1 if grid[index][column] == 'E' else 0

if grid[row][column] == '0':
result = max(result, row_count + column_count[column])
return result


solution = Solution()
grid = [['0', 'E', '0', '0'],
['E', '0', 'W', 'E'],
['0', 'E', '0', '0']]
print solution.maxKilledEnemies(grid)
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/).
|387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [Python](./300-400q/387.py)|Easy|
|380|[Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [Python](./300-400q/380.py)|Hard|
|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|
|361|[Bomb Enemy](https://leetcode.com/problems/bomb-enemy)|[Python](./300-400q/361.py)|Medium|
|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [Python](./300-400q/350.py)|Easy|
|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [Python](./300-400q/347.py)|Medium|
|346|[Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream)|[Python](./300-400q/346.py)|Easy|
Expand Down

0 comments on commit b3ee24c

Please sign in to comment.