public int maxKilledEnemies(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0)
return 0;
int ans = 0;
int m = grid.length, n = grid[0].length;
int[][] left2right = new int[m][n];
int[][] right2left = new int[m][n];
int[][] top2bottom = new int[m][n];
int[][] bottom2top = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int k = n - 1 - j;
if (grid[i][j] == 'W') {
left2right[i][j] = 0;
} else {
if (j > 0) {
left2right[i][j] = left2right[i][j - 1] + (grid[i][j - 1] == 'E' ? 1 : 0);
}
}
if (grid[i][k] == 'W') {
right2left[i][k] = 0;
} else {
if (k < n - 1) {
right2left[i][k] = right2left[i][k + 1] + (grid[i][k + 1] == 'E' ? 1 : 0);
}
}
}
}
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
if (grid[i][j] == 'W') {
top2bottom[i][j] = 0;
} else {
if (i > 0)
top2bottom[i][j] = top2bottom[i - 1][j] + (grid[i - 1][j] == 'E' ? 1 : 0);
}
int k = m - 1 - i;
if (grid[k][j] == 'W') {
bottom2top[k][j] = 0;
} else {
if (k < m - 1)
bottom2top[k][j] = bottom2top[k + 1][j] + (grid[k + 1][j] == 'E' ? 1 : 0);
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '0') {
int count = left2right[i][j] + right2left[i][j] + top2bottom[i][j] + bottom2top[i][j];
ans = Math.max(ans, count);
}
}
}
return ans;
}