Leetcode 361. Bomb Enemy

来源:互联网 发布:mac os系统怎么安装 编辑:程序博客网 时间:2024/06/14 15:39

Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum enemies you can kill using one bomb.
The bomb kills 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.
Note that you can only put the bomb at an empty cell.

Example:

For the given grid0 E 0 0E 0 W E0 E 0 0return 3. (Placing a bomb at (1,1) kills 3 enemies)


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 max = 0;        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if (grid[i][j] != '0') continue;                int cnt = helper(grid, i, j);                max = Math.max(cnt, max);            }        }          return max;    }        private int helper(char[][] grid, int i, int j) {        int cnt = 0;                for (int up = i + 1; up < grid.length; up++) {            if (grid[up][j] == 'W') break;            if (grid[up][j] == 'E') cnt++;        }        for (int down = i - 1; down >= 0; down--) {            if (grid[down][j] == 'W') break;            if (grid[down][j] == 'E') cnt++;        }        for (int right = j + 1; right < grid[0].length; right++) {            if (grid[i][right] == 'W') break;            if (grid[i][right] == 'E') cnt++;        }        for (int left = j - 1; left >= 0; left--) {            if (grid[i][left] == 'W') break;            if (grid[i][left] == 'E') cnt++;        }        return cnt;    }


public int maxKilledEnemies(char[][] grid) {        if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;        int max = 0;        int row = 0;        int m = grid.length, n = grid[0].length;        int[] col = new int[n];        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if (grid[i][j] == 'W') continue;                if (j == 0 || grid[i][j - 1] == 'W') row = get_row(grid, i, j);                if (i == 0 || grid[i - 1][j] == 'W') col[j] = get_col(grid, i, j);                if (grid[i][j] == '0') max = Math.max(max, row + col[j]);            }        }        return max;    }        private int get_col(char[][] grid, int i, int j) {        int cnt = 0;        while (i < grid.length && grid[i][j] != 'W') {            if (grid[i][j] == 'E') cnt++;            i++;        }        return cnt;    }    private int get_row(char[][] grid, int i, int j) {        int cnt = 0;        while (j < grid[0].length && grid[i][j] != 'W') {            if (grid[i][j] == 'E') cnt++;            j++;        }        return cnt;    }