|
| 1 | +public class Solution { |
| 2 | + public int maxKilledEnemies(char[][] grid) { |
| 3 | + int maxKill = 0; |
| 4 | + |
| 5 | + // find empty cells |
| 6 | + for (int r = 0; r < grid.length; r++) { |
| 7 | + for (int c = 0; c < grid[r].length; c++) { |
| 8 | + int kill = 0; |
| 9 | + if (grid[r][c] == '0') { |
| 10 | + int row = r; |
| 11 | + while (--row >= 0 && grid[row][c] != 'W') { |
| 12 | + if (grid[row][c] == 'E') kill++; |
| 13 | + } |
| 14 | + row = r; |
| 15 | + while (++row < grid.length && grid[row][c] != 'W') { |
| 16 | + if (grid[row][c] == 'E') kill++; |
| 17 | + } |
| 18 | + |
| 19 | + int col = c; |
| 20 | + while (--col >= 0 && grid[r][col] != 'W') { |
| 21 | + if (grid[r][col] == 'E') kill++; |
| 22 | + } |
| 23 | + col = c; |
| 24 | + while (++col < grid[r].length && grid[r][col] != 'W') { |
| 25 | + if (grid[r][col] == 'E') kill++; |
| 26 | + } |
| 27 | + if (kill > maxKill) { |
| 28 | + maxKill = kill; |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + return maxKill; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | + |
| 38 | +// DP-ish solution for ref: https://discuss.leetcode.com/topic/50374/java-dp-solultion-o-mn-time-o-mn-space-beats-90 |
| 39 | +public class Solution { |
| 40 | + public int maxKilledEnemies(char[][] grid) { |
| 41 | + if (grid == null || grid.length == 0 || grid[0].length == 0) return 0; |
| 42 | + |
| 43 | + int m = grid.length; |
| 44 | + int n = grid[0].length; |
| 45 | + int[][] dp = new int[m][n]; |
| 46 | + |
| 47 | + // from left to right |
| 48 | + for (int i = 0; i < m; i++) { |
| 49 | + int current = 0; |
| 50 | + for (int j = 0; j < n; j++) |
| 51 | + current = process(grid, dp, i, current, j); |
| 52 | + } |
| 53 | + // from top to bottom |
| 54 | + for (int j = 0; j < n; j++) { |
| 55 | + int current = 0; |
| 56 | + for (int i = 0; i < m; i++) |
| 57 | + current = process(grid, dp, i, current, j); |
| 58 | + } |
| 59 | + // from right to left |
| 60 | + for (int i = 0; i < m; i++) { |
| 61 | + int current = 0; |
| 62 | + for (int j = n - 1; j >= 0; j--) |
| 63 | + current = process(grid, dp, i, current, j); |
| 64 | + } |
| 65 | + int ans = 0; |
| 66 | + // from bottom to top |
| 67 | + for (int j = 0; j < n; j++) { |
| 68 | + int current = 0; |
| 69 | + for (int i = m - 1; i >= 0; i--) { |
| 70 | + current = process(grid, dp, i, current, j); |
| 71 | + if (grid[i][j] == '0') ans = Math.max(ans, dp[i][j]); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return ans; |
| 76 | + } |
| 77 | + |
| 78 | + private int process(char[][] c, int[][] dp, int i, int current, int j) { |
| 79 | + if (c[i][j] == 'W') current = 0; |
| 80 | + if (c[i][j] == 'E') current++; |
| 81 | + dp[i][j] += current; |
| 82 | + return current; |
| 83 | + } |
| 84 | +} |
0 commit comments