dp
分别计算从左到右、从右到左、从上到下、从下到上4个方向可能的值,然后计算所有为‘0’的地方的4个方向的值的最大值
https://www.cnblogs.com/grandyang/p/5599289.html
class Solution { public: /** * @param grid: Given a 2D grid, each cell is either 'W', 'E' or '0' * @return: an integer, the maximum enemies you can kill using one bomb */ int maxKilledEnemies(vector<vector<char> > &grid) { // write your code here int m = grid.size(); if(m <= 0) return 0; int n = grid[0].size(); if(n <= 0) return 0; vector<vector<int> > left(m,vector<int>(n,0)),right(m,vector<int>(n,0)),top(m,vector<int>(n,0)),down(m,vector<int>(n,0)); for(int i = 0;i < m;i++){ for(int j = 0;j < n;j++){ int tmp; if(j == 0 || grid[i][j] == 'W') tmp = 0; else tmp = left[i][j-1]; if(grid[i][j] == 'E') left[i][j] = tmp + 1; else left[i][j] = tmp; } } for(int i = 0;i < m;i++){ for(int j = n - 1;j >= 0;j--){ int tmp; if(j == n - 1 || grid[i][j] == 'W') tmp = 0; else tmp = right[i][j+1]; if(grid[i][j] == 'E') right[i][j] = tmp + 1; else right[i][j] = tmp; } } for(int j = 0;j < n;j++){ for(int i = 0;i < m;i++){ int tmp; if(i == 0 || grid[i][j] == 'W') tmp = 0; else tmp = top[i-1][j]; if(grid[i][j] == 'E') top[i][j] = tmp + 1; else top[i][j] = tmp; } } for(int j = 0;j < n;j++){ for(int i = m-1;i >= 0;i--){ int tmp; if(i == m-1 || grid[i][j] == 'W') tmp = 0; else tmp = down[i+1][j]; if(grid[i][j] == 'E') down[i][j] = tmp + 1; else down[i][j] = tmp; } } int max_num = 0; for(int i = 0;i < m;i++){ for(int j = 0;j < n;j++){ if(grid[i][j] == '0') max_num = max(max_num,left[i][j] + right[i][j] + top[i][j] + down[i][j]); } } return max_num; } };