brute force beats 98%..


  • 0
    Z
    class Solution {
        public int maxKilledEnemies(char[][] grid) {
            if (grid == null || grid.length == 0) return 0;
            int n = grid.length, m = grid[0].length;
            int res = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[i].length; j++) {
                    if (grid[i][j] == '0') res = Math.max(res, search(grid, i, j));
                }
            }
            return res;
        }
        
        private int search(char[][] grid, int x, int y) {
            int ans = 0;
            /* from position (x, y) to (x, 0) */
            for (int i = y; i >= 0; i--) {
                if (grid[x][i] == 'W') break;
                else if (grid[x][i] == 'E') ans++;
            }
            
            /* from position (x, y) to (x, m) */
            for (int i = y; i < grid[0].length; i++) {
                if (grid[x][i] == 'W') break;
                else if (grid[x][i] == 'E') ans++;
            }
            
            /* from position (x, y) to (0, y) */
            for (int i = x; i >= 0; i--) {
                if (grid[i][y] == 'W') break;
                else if (grid[i][y] == 'E') ans++;
            }
            
            /* from position (x, y) to (n, y) */
            for (int i = x; i < grid.length; i++) {
                if (grid[i][y] == 'W') break;
                else if (grid[i][y] == 'E') ans++;
            }
            return ans;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.