# 【LeetCode】361. Bomb Enemy 解题报告(C++)

900 篇文章 170 订阅
1033 篇文章 59 订阅

## 题目描述

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: You can only put the bomb at an empty cell.

Example:

Input: [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
Output: 3
Explanation: For the given grid,

0 E 0 0
E 0 W E
0 E 0 0

Placing a bomb at (1,1) kills 3 enemies.


## 解题方法

### 暴力搜索

C++代码如下：

class Solution {
public:
int maxKilledEnemies(vector<vector<char>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int res = 0;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[0].size(); ++j) {
if (grid[i][j] == '0') {
res = max(res, killEnemies(grid, i, j));
}
}
}
return res;
}
int killEnemies(vector<vector<char>>& grid, int x, int y) {
int count = 0;
for (vector<int>& curd : dirs) {
int newx = x;
int newy = y;
while (newx >= 0 && newx < grid.size() && newy >= 0 && newy < grid[0].size()
&& grid[newx][newy] != 'W') {
if (grid[newx][newy] == 'E')
count ++;
newx += curd[0];
newy += curd[1];
}
}
return count;
}
private:
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
};


## 日期

2019 年 9 月 20 日 —— 是选择中国互联网式加班？还是外企式养生？

• 0
点赞
• 0
收藏
• 打赏
• 0
评论
03-20
05-27 857
12-25 473
06-18 9256
08-16 1537
07-03 178
06-19 1843
07-14 195
06-01 290
04-01 83
10-25 1074

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。