Leetcode 361 Solution

This article provides solution to leetcode question 361 (bomb-enemy)

https://leetcode.com/problems/bomb-enemy

Solution

class Solution {
public:
    int maxKilledEnemies(vector<vector<char>>& grid) {
        if (grid.size() == 0 || grid[0].size() == 0)
            return 0;

        int m = grid.size();
        int n = grid[0].size();

        int up[m][n];
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (i == 0 || grid[i - 1][j] == 'W')
                    up[i][j] = grid[i][j] == 'E';
                else
                    up[i][j] = up[i - 1][j] + (grid[i][j] == 'E');
            }
        }

        int down[m][n];
        for (int i = m - 1; i >= 0; i--)
        {
            for (int j = 0; j < n; j++)
            {
                if (i == m - 1 || grid[i + 1][j] == 'W')
                    down[i][j] = grid[i][j] == 'E';
                else
                    down[i][j] = down[i + 1][j] + (grid[i][j] == 'E');
            }
        }

        int left[m][n];
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (j == 0 || grid[i][j - 1] == 'W')
                    left[i][j] = grid[i][j] == 'E';
                else
                    left[i][j] = left[i][j - 1] + (grid[i][j] == 'E');
            }
        }

        int right[m][n];
        for (int i = 0; i < m; i++)
        {
            for (int j = n - 1; j >= 0; j--)
            {
                if (j == n - 1 || grid[i][j + 1] == 'W')
                    right[i][j] = grid[i][j] == 'E';
                else
                    right[i][j] = right[i][j + 1] + (grid[i][j] == 'E');
            }
        }

        int max_number = 0;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] != '0')
                    continue;

                int number = up[i][j] + down[i][j] + left[i][j] + right[i][j];
                max_number = max(max_number, number);
            }
        }

        return max_number;
    }
};