Skip to content

Commit e7b7adc

Browse files
committed
Add a solution to Bomb Enemy
1 parent cc7ea56 commit e7b7adc

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Array/BombEnemy.swift

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/bomb-enemy/
3+
* Primary idea: Greedy. Update the result only when there is wall or at the beginning.
4+
* Time Complexity: O(mn), Space Complexity: O(n)
5+
*
6+
*/
7+
8+
class BombEnemy {
9+
func maxKilledEnemies(_ grid: [[Character]]) -> Int {
10+
let m = grid.count, n = grid[0].count
11+
var res = 0, rowHit = 0, colHit = Array(repeating: 0, count: n)
12+
13+
for i in 0..<m {
14+
for j in 0..<n {
15+
16+
// check row
17+
if j == 0 || grid[i][j - 1] == "W" {
18+
rowHit = 0
19+
for y in j..<n {
20+
if grid[i][y] == "W" {
21+
break
22+
}
23+
if grid[i][y] == "E" {
24+
rowHit += 1
25+
}
26+
}
27+
}
28+
29+
// check col
30+
if i == 0 || grid[i - 1][j] == "W" {
31+
colHit[j] = 0
32+
for x in i..<m {
33+
if grid[x][j] == "W" {
34+
break
35+
}
36+
if grid[x][j] == "E" {
37+
colHit[j] += 1
38+
}
39+
}
40+
}
41+
42+
if grid[i][j] == "0" {
43+
res = max(res, rowHit + colHit[j])
44+
}
45+
}
46+
}
47+
48+
return res
49+
}
50+
}

0 commit comments

Comments
 (0)