Bob and Bombs

Bob and Khatu are brave soldiers in World War 3. They have spotted an enemy troop that is planting bombs. They sent a message to the command center containing characters W and B where W represents a wall and B represents a Bomb. They asked command to tell them how many walls will be destroyed if all bombs explode at once. One bomb can destroy 2 walls on both sides.

Example:

Input:  s = "WWBWWBW"
Output: 5

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int bobAndBombs(string s)
{

    int n = s.size();
    int cnt = 0;
    for (int i = 0i < ni++)
    {
        if (i == 0)
        {
            if (s[i] == 'B')
            {
                for (int j = i + 1j <= min(i + 2n - 1); j++)
                {
                    if (s[j] == 'W')
                    {
                        cnt++;
                        s[j] = '.';
                    }
                }
            }
        }
        else if (i == n - 1)
        {
            if (s[i] == 'B')
            {
                for (int j = i - 1j >= max(0i - 2); j--)
                {
                    if (s[j] == 'W')
                    {
                        cnt++;
                        s[j] = '.';
                    }
                }
            }
        }
        else
        {
            if (s[i] == 'B')
            {
                for (int j = i - 1j >= max(0i - 2); j--)
                {
                    if (s[j] == 'W')
                    {
                        cnt++;
                        s[j] = '.';
                    }
                }
                for (int j = i + 1j <= min(n - 1i + 2); j++)
                {
                    if (s[j] == 'W')
                    {
                        cnt++;
                        s[j] = '.';
                    }
                }
            }
        }
    }
    return cnt;
}
int main()
{

    string s = "WWBWWBW";

    cout << bobAndBombs(s<< "\n";

    return 0;
}


No comments:

Post a Comment