File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments