Copy 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)
Copy class Solution {
public int maxKilledEnemies ( char [][] grid) {
if (grid == null || grid . length == 0 || grid[ 0 ] . length == 0 ) {
return 0 ;
}
int m = grid . length , n = grid[ 0 ] . length ;
int [][] table = new int [m][n];
int res = 0 ;
for ( int i = 0 ; i < m; i ++ ) {
for ( int j = 0 ; j < n; j ++ ) {
if (grid[i][j] == '0' ) {
table[i][j] += getEnemies(i , j , grid , true ) ;
table[i][j] += getEnemies(i , j , grid , false ) ;
res = Math . max (res , table[i][j]);
}
}
}
return res;
}
public int getEnemies ( int row , int col , char [][] grid , boolean isRow) {
int enemies = 0 ;
int i = row;
int j = col;
if (isRow) {
while (j < grid[ 0 ] . length && grid[row][j] != 'W' ) {
if (grid[row][j] == 'E' ) {
++ enemies;
}
++ j;
}
j = col;
while (j >= 0 && grid[row][j] != 'W' ) {
if (grid[row][j] == 'E' ) {
++ enemies;
}
-- j;
}
}
else {
while (i < grid . length && grid[i][col] != 'W' ) {
if (grid[i][col] == 'E' ) {
++ enemies;
}
++ i;
}
i = row;
while (i >= 0 && grid[i][col] != 'W' ) {
if (grid[i][col] == 'E' ) {
++ enemies;
}
-- i;
}
}
return enemies;
}
}
Copy class Solution {
public int maxKilledEnemies ( char [][] grid) {
if (grid == null || grid . length == 0 || grid[ 0 ] . length == 0 ) {
return 0 ;
}
int m = grid . length , n = grid[ 0 ] . length ;
int res = 0 ;
int rowHits = 0 ;
int [] colHits = new int [n];
for ( int i = 0 ; i < m; i ++ ) {
for ( int j = 0 ; j < n; j ++ ) {
if (j == 0 || grid[i][j - 1 ] == 'W' ) {
rowHits = 0 ;
for ( int k = j; k < n && grid[i][k] != 'W' ; k ++ ) {
if (grid[i][k] == 'E' ) {
++ rowHits;
}
}
}
if (i == 0 || grid[i - 1 ][j] == 'W' ) {
colHits[j] = 0 ;
for ( int k = i; k < m && grid[k][j] != 'W' ; k ++ ) {
if (grid[k][j] == 'E' ) {
++ colHits[j];
}
}
}
if (grid[i][j] == '0' ) {
res = Math . max (res , rowHits + colHits[j]);
}
}
}
return res;
}
}
3. Time & Space Complexity