We have a 2D grid. Each cell is either a wall, an enemy or empty.
For example (0-empty, X-enemy, Y-wall):
0 X 0 0
X 0 Y X
0 X 0 0
You have one bomb and you want to kill as many as possible enemies with it. The bomb will kill 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.
Given such a grid, return the maximum enemies you can kill with one bomb.
Note that you can only put the bomb at empty cell.
Note that you can only put the bomb at empty cell.
In the example, if you put a bomb at (1,1) you will kill 3 enemies which is the best you can get. You can not kill the guy behind the wall at (1,3).
Dp version which is similar to Leetcode 317. Shortest Distance from All Buildings
#include <string>
#include <iostream>
#include <vector>
using namespace std; // this method will take O(n*m*(n+m)) time complexity.
void bfs(vector< vector<char> >& matrix, vector< vector<int> >& steps, int i, int j) {
for(int k = i; k >= 0 && (matrix[k][j] != 'Y'); --k) {
steps[k][j] += 1;
}
for(int k = i + 1; k < matrix.size() && (matrix[k][j] != 'Y'); ++k) {
steps[k][j] += 1;
}
for(int k = j; k >= 0 && (matrix[i][k] != 'Y'); --k) {
steps[i][k] += 1;
}
for(int k = j + 1; k < matrix[0].size() && (matrix[i][k] != 'Y'); ++k) {
steps[i][k] += 1;
}
}
int bombEnemies(vector< vector<char> >& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector< vector<int> > steps(m, vector<int>(n, 0));
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
if(matrix[i][j] == 'X') {
bfs(matrix, steps, i, j);
}
}
}
int maxValue = 0;
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
cout << steps[i][j] << " ";
maxValue = max(maxValue, steps[i][j]);
}
cout << endl;
}
return maxValue;
}
int main(void) {
vector< vector<char> > matrix{
{'O', 'X', 'O', 'O'},
{'X', 'O', 'Y', 'X'},
{'O', 'X', 'O', 'O'}};
cout << bombEnemies(matrix) << endl;
}
To optimize it, we can pre-cache the each column bombed values in column[] and calculate each row bomb values at the fly.
int bombEnemies(vector< vector<char> >& matrix) {
int maxNumber = 0;
int rowHit = 0;
int rows = matrix.size();
int cols = matrix[0].size();
vector<int> colsBomb(rows, 0);
for(int i = 0; i < rows; ++i) {
for(int j = 0; j < cols; ++j) {
if(!j || (matrix[i][j-1] == 'Y')) { // if we met the 'Y', need to recalculate the rowhit
rowHit = 0;
for(int k = j; k < cols && matrix[i][k] != 'Y'; ++k) {
rowHit += (matrix[i][k] == 'X');
}
}
if(!i || (matrix[i-1][j] == 'Y')) { // if met the 'Y', need to recalculate the colhit.
colsBomb[j] = 0;
for(int k = i; k < rows && matrix[k][j] != 'Y'; ++k) {
colsBomb[j] += (matrix[k][j] == 'X');
}
}
if(matrix[i][j] == '0') {
maxNumber = max(maxNumber, rowHit + colsBomb[j]);
}
}
}
return maxNumber;
}
int main(void) {
vector< vector<char> > matrix {
{'0', 'X', 'X'},
{'X', '0', '0'},
{'0', 'Y', 'X'}};
cout << bombEnemies(matrix) << endl;
}