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; }
阅读全文
0 0
- LeetCode 361. Bomb Enemy
- Leetcode 361. Bomb Enemy
- [leetcode] 361. Bomb Enemy 解题报告
- Leetcode 361. Bomb Enemy (Medium) (cpp)
- [Leetcode] 361. Bomb Enemy 解题报告
- [leetcode][361]bomb enemy
- 361. Bomb Enemy
- LeetCode 361. Boom Enemy
- enemy
- Bomb
- Bomb
- Bomb
- Bomb
- Bomb
- bomb
- Bomb
- Bomb
- bomb
- #WEBGIS#校园地图系统开发- 5、SLD专题介绍使用技巧
- (转)区块链上的股市:十年后传统股市还会存在吗?
- android studio 调试技巧(简直太好用)
- 合并有序链表 计算1加到n不用条件判断
- 【LectCode】515. Find Largest Value in Each Tree Row
- Leetcode 361. Bomb Enemy
- 快速排序
- 分治例题
- 嵌入式Linux入门7:kernel移植
- #WEBGIS#校园地图系统开发-6、多图层发布方案
- (转)为什么证券行业的软件研发水平远低于互联网科技公司?
- 嵌入式Linux入门8:rootfs移植
- 暑假写题第五天
- ufldl学习笔记与编程作业:Softmax Regression(Softmax 回归)