Leetcode 361. Bomb Enemy (Medium) (cpp)

Leetcode 361. Bomb Enemy (Medium) (cpp)

Tag: Dynamic Programming

Difficulty: Medium


/*

361. Bomb Enemy (Medium)

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 {
public:
	int maxKilledEnemies(vector<vector<char>>& grid) {
		if (grid.size() == 0 || grid[0].size() == 0) {
			return 0;
		}
		int col = grid[0].size(), row = grid.size();
		vector<vector<int>> vrl(row, vector<int>(col)), vbu(row, vector<int>(col));
		for (int j = col - 1; j >= 0; j--) {
			for (int i = row - 1; i >= 0; i--) {
				if (grid[i][j] != 'W') {
					int e = grid[i][j] == 'E';
					vrl[i][j] = j == col - 1 ? e : e + vrl[i][j + 1];
					vbu[i][j] = i == row - 1 ? e : e + vbu[i + 1][j];
				}
			}
		}
		vector<int> vlr(row), vub(col);
		int res = 0;
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				if (grid[i][j] == '0') {
					res = max(vlr[i] + vrl[i][j] + vub[j] + vbu[i][j], res);
				}
				else {
					vub[j] = grid[i][j] == 'W' ? 0 : vub[j] + 1;
					vlr[i] = grid[i][j] == 'W' ? 0 : vlr[i] + 1;
				}
			}
		}
		return res;
	}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章