The Bomberman Game HackerRank Solution in C, C++, Java, Python

Bomberman lives in a rectangular grid. Each cell in the grid either contains a bomb or nothing at all.

Each bomb can be planted in any cell of the grid but once planted, it will detonate after exactly 3 seconds. Once a bomb detonates, it’s destroyed — along with anything in its four neighboring cells. This means that if a bomb detonates in cell i,j, any valid cells (i+1,j)and (i,j+1) are cleared. If there is a bomb in a neighboring cell, the neighboring bomb is destroyed without detonating, so there’s no chain reaction.

  • Bomberman is immune to bombs, so he can move freely throughout the grid. Here’s what he does:
  • Initially, Bomberman arbitrarily plants bombs in some of the cells, the initial state.
  • After one second, Bomberman does nothing.
  • After one more second, Bomberman plants bombs in all cells without bombs, thus filling the whole grid with bombs. No bombs detonate at this point.
  • After one more second, any bombs planted exactly three seconds ago will detonate. Here, Bomberman stands back and observes.
  • Bomberman then repeats steps 3 and 4 indefinitely.

Note that during every second Bomberman plants bombs, the bombs are planted simultaneously (i.e., at the exact same moment), and any bombs planted at the same time will detonate at the same time.

Given the initial configuration of the grid with the locations of Bomberman’s first batch of planted bombs, determine the state of the grid after N seconds.

For example, if the initial grid looks like:

...
.O.
...

it looks the same after the first second. After the second second, Bomberman has placed all his charges:

OOO
OOO
OOO

At the third second, the bomb in the middle blows up, emptying all surrounding cells:

...
...
...

Function Description

Complete the bomberMan function in the editory below. It should return an array of strings that represent the grid in its final state.

bomberMan has the following parameter(s):

n: an integer, the number of seconds to simulate
grid: an array of strings that represents the grid

Input Format

The first line contains three space-separated integers r, c, and n, The number of rows, columns and seconds to simulate.
Each of the next r lines contains a row of the matrix as a single string of c characters. The . character denotes an empty cell, and the O character (ascii 79) denotes a bomb.

Output Format

Print the grid’s final state. This means R lines where each line contains C characters, and each character is either a . or an O (ascii 79). This grid must represent the state of the grid after n seconds.

Sample Input

6 7 3
.......
...O...
....O..
.......
OO.....
OO.....

Sample Output

OOO.OOO
OO...OO
OOO...O
..OO.OO
...OOOO
...OOOO

Explanation

The initial state of the grid is:

.......
...O...
....O..
.......
OO.....
OO.....

Bomberman spends the first second doing nothing, so this is the state after 1 second:

.......
...O...
....O..
.......
OO.....
OO.....

Bomberman plants bombs in all the empty cells during his second second, so this is the state after 2 seconds:

OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO

In his third second, Bomberman sits back and watches all the bombs he planted 3 seconds ago detonate. This is the final state after  seconds:

OOO.OOO
OO...OO
OOO...O
..OO.OO
...OOOO
...OOOO

The Bomberman Game HackerRank Solution in C

#include <stdio.h>

#define MAX_ROW_COL				(201)
#define BOMB					(79)
#define EMPTY					('.')
#define TEMP					('A')

typedef int INT32;

char gGrid[MAX_ROW_COL][MAX_ROW_COL];

int main(void)
{	
    INT32 nLpCnt1, nR, nC, nS, nLpCnt2, ndCnt;

    //read nN, nK
    scanf("%d%d%d", &nR, &nC, &nS);

    //read the matrix
    for(nLpCnt1 = 0; nLpCnt1 < nR; nLpCnt1++)
        scanf("%s", gGrid[nLpCnt1]);

    if(nS < 2)
    {
        for(nLpCnt1 = 0; nLpCnt1 < nR; nLpCnt1++)
            printf("%s\n", gGrid[nLpCnt1]);
        return 0;
    }

    nS %= 4; 

    if((nS == 0) || (nS == 2))	//all bombs
    {
        for(nLpCnt1 = 0; nLpCnt1 < nR; nLpCnt1++)
            for(nLpCnt2 = 0; nLpCnt2 < nC; nLpCnt2++)
                gGrid[nLpCnt1][nLpCnt2] = BOMB;
    }
    else 	//bombs detonated once or twice
    {
        if(nS == 3)
            nS = 1;
        else 
            nS = 2;
        for(ndCnt = 0; ndCnt < nS; ndCnt++)
        {
            for(nLpCnt1 = 0; nLpCnt1 < nR; nLpCnt1++)
            {
                //form the array with temp
                for(nLpCnt2 = 0; nLpCnt2 < nC; nLpCnt2++)
                {
                    if(gGrid[nLpCnt1][nLpCnt2] == BOMB)
                    {
                        gGrid[nLpCnt1][nLpCnt2] = TEMP;

                        if(nLpCnt1 > 0)
                        {
                            gGrid[nLpCnt1 - 1][nLpCnt2] = TEMP;	
                        }

                        if(nLpCnt2 > 0)
                        {
                            gGrid[nLpCnt1][nLpCnt2 - 1] = TEMP;	
                        }

                        if(((nLpCnt1 + 1) < nR) && (gGrid[nLpCnt1 + 1][nLpCnt2] != BOMB))
                        {
                            gGrid[nLpCnt1 + 1][nLpCnt2] = TEMP;	
                        }

                        if(((nLpCnt2 + 1) < nC) && (gGrid[nLpCnt1][nLpCnt2 + 1] != BOMB))
                        {
                            gGrid[nLpCnt1][nLpCnt2 + 1] = TEMP;	
                        }
                        
                    }
                        
                }
            }

            //convert empty to bombs and temp to empty
            for(nLpCnt1 = 0; nLpCnt1 < nR; nLpCnt1++)
            {
                //form the array with temp
                for(nLpCnt2 = 0; nLpCnt2 < nC; nLpCnt2++)
                {
                    if(gGrid[nLpCnt1][nLpCnt2] == EMPTY)
                        gGrid[nLpCnt1][nLpCnt2] = BOMB;
                    else
                        gGrid[nLpCnt1][nLpCnt2] = EMPTY;
                }
            }
        }
                        
    }

    for(nLpCnt1 = 0; nLpCnt1 < nR; nLpCnt1++)
        printf("%s\n", gGrid[nLpCnt1]);
        
    return 0;
}

 

The Bomberman Game HackerRank Solution in C++

#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
char ch[300];
int n,m,T,pd[300][300],bo[300][300];
const int gox[4]={1,-1,0,0},goy[4]={0,0,1,-1};
void print(){
    for (int i=1;i<=n;i++){
        for (int j=1;j<=m;j++) if (pd[i][j]==0) putchar('.'); else putchar('O');
        cout<<endl;
    }
}
int main(){
    scanf("%d%d%d",&n,&m,&T);
    for (int i=1;i<=n;i++){
        scanf("%s",ch+1);
        for (int j=1;j<=m;j++) pd[i][j]=(ch[j]=='O');
    }
    if (T==1){
        print(); return 0;
    }
    if (T%2==0){
        for (int i=1;i<=n;i++)
            for (int j=1;j<=m;j++) pd[i][j]=1;
        print(); return 0;
    }
    memcpy(bo,pd,sizeof bo);
    for (int i=1;i<=n;i++)
        for (int j=1;j<=m;j++)
            for (int k=0;k<4;k++)
                pd[i][j]|=bo[i+gox[k]][j+goy[k]];
    if ((T/2)%2==0){
        memcpy(bo,pd,sizeof bo);
        for (int i=1;i<=n;i++)
            for (int j=1;j<=m;j++){
                pd[i][j]=bo[i][j];
                for (int k=0;k<4;k++)
                    if (i+gox[k]>0&&i+gox[k]<=n&&j+goy[k]>0&&j+goy[k]<=m&&bo[i+gox[k]][j+goy[k]]==0) pd[i][j]=0;
            }
        print();
    }else {
        for (int i=1;i<=n;i++)
            for (int j=1;j<=m;j++) pd[i][j]^=1;
        print();
    }
}

 

The Bomberman Game HackerRank Solution in Java

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*; 
import java.util.*;
import java.util.regex.*;



public class Solution {
    private static BufferedReader br;
    private static StringTokenizer st;
    private static PrintWriter pw;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int qq = 1;
        //int qq = Integer.MAX_VALUE;
        //int qq = readInt();
        for(int casenum = 1; casenum <= qq; casenum++) {
            int r = readInt();
            int c = readInt();
            int n = readInt();
            n--;
            int[][] bomb = new int[r][c];
            for(int i = 0; i < r; i++) {
                String s = nextToken();
                for(int j = 0; j < c; j++) {
                    if(s.charAt(j) == 'O') {
                        bomb[i][j] = 2;
                    }
                }
            }
            n %= 100;
            int[] dx = new int[]{-1,1,0,0};
            int[] dy = new int[]{0,0,-1,1};
            for(int i = 1; i <= n; i++) {
                if(i%2 == 1) {
                    for(int a = 0; a < r; a++) {
                        for(int b = 0; b < c; b++) {
                            if(bomb[a][b] == 0) {
                                bomb[a][b] = 3;
                            }
                            else if(bomb[a][b] > 0) {
                                bomb[a][b]--;
                            }
                        }
                    }
                }
                else {
                    boolean[][] dead = new boolean[r][c];
                    for(int a = 0; a < r; a++) {
                        for(int b = 0; b < c; b++) {
                            if(bomb[a][b] == 1) { 
                                dead[a][b] = true;
                                for(int k = 0; k < dx.length; k++) {
                                    int nx = a + dx[k];
                                    int ny = b + dy[k];
                                    if(nx >= 0 && nx < r && ny >= 0 && ny < c) {
                                        dead[nx][ny] = true;
                                    }
                                }
                            }
                        }
                    }
                    for(int a = 0; a < r; a++) {
                        for(int b = 0; b < c; b++) {
                            if(dead[a][b])
                                bomb[a][b] = 0;
                            else if(bomb[a][b] > 0) {
                                bomb[a][b]--;
                            }
                        }
                    }
                }
            }
            for(int[] out: bomb) {
                for(int out2: out) {
                    if(out2 > 0) {
                        pw.print('O');
                    }
                    else {
                        pw.print('.');
                    }
                }
                pw.println();
            }
        }
        exitImmediately();
    }

    private static void exitImmediately() {
        pw.close();
        System.exit(0);
    }

    private static long readLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    private static double readDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    private static int readInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    private static String nextLine() throws IOException  {
        if(!br.ready()) {
            exitImmediately();
        }
        st = null;
        return br.readLine();
    }

    private static String nextToken() throws IOException  {
        while(st == null || !st.hasMoreTokens())  {
            if(!br.ready()) {
                exitImmediately();
            }
            st = new StringTokenizer(br.readLine().trim());
        }
        return st.nextToken();
    }
}

 

The Bomberman Game HackerRank Solution in Python

#!/usr/bin/python

import os
import sys
import itertools
import copy

def solve(f):
    r, c, n = f.read_int_list()
    m = [ list(f.read_str()) for _ in xrange(r) ]

    s = [[0]*c for _ in xrange(r)]
    t = 1
    for i in xrange(r):
        for j in xrange(c):
            if m[i][j] == 'O': s[i][j] = 2

    if n > 5: n -= (n-8)/4 * 4

    while t < n:
        t += 1
        if t%2 == 0:
            for i in xrange(r):
                for j in xrange(c):
                    if s[i][j] > 0:
                        s[i][j] -= 1
                    else:
                        s[i][j] = 3
        else:
            b = [[False]*c for _ in xrange(r)]
            for i in xrange(r):
                for j in xrange(c):
                    s[i][j] -= 1
                    if s[i][j] == 0:
                        b[i][j] = True
                        if i > 0: b[i-1][j] = True
                        if j > 0: b[i][j-1] = True
                        if i < r-1: b[i+1][j] = True
                        if j < c-1: b[i][j+1] = True
            for i in xrange(r):
                for j in xrange(c):
                    if b[i][j]: s[i][j] = 0

        if all(map(lambda x: all([i==0 for i in x]), s)): break

    for i in xrange(r):
        for j in xrange(c):
            m[i][j] = '.' if s[i][j] == 0 else 'O'

    return '\n'.join(map(lambda x: ''.join(x),m))

class Reader(object):
    def __init__(self, filename=None):
        self.test_mode = filename is not None
        self.cases = 1
        self.buffer = []
        if self.test_mode:
            with open(filename) as f:
                blank_flg = False
                for line in f:
                    line = line.strip()
                    if line:
                        self.buffer.append(line)
                        blank_flg = False
                    else:
                        if not blank_flg: self.cases += 1
                        blank_flg = True

    def __readline(self):
        return self.buffer.pop(0) if self.test_mode else raw_input()

    def read_int(self):
        return int(self.__readline())
    def read_float(self):
        return float(self.__readline())
    def read_long(self):
        return long(self.__readline())
    def read_str(self):
        return self.__readline()

    def read_int_list(self):
        return [int(item) for item in self.__readline().split()]
    def read_float_list(self):
        return [float(item) for item in self.__readline().split()]
    def read_long_list(self):
        return [long(item) for item in self.__readline().split()]
    def read_str_list(self):
        return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv)>1 else None
    f = Reader(filename)
    if f.test_mode:
        for c in xrange(f.cases):
            print "Case #%d"%(c+1)
            print solve(f)
    else:
        print solve(f)

 

The Bomberman Game HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

class Solution {
    static void Main(String[] args) {
        string[] tokens = Console.ReadLine().Split(' ');
        int rows = Convert.ToInt32(tokens[0]);
        int columns = Convert.ToInt32(tokens[1]);
        int seconds = Convert.ToInt32(tokens[2]);
        List<string> steps = new List<string>();

        char[][] map = new char[rows][];
        for (int i = 0; i < rows; ++i)
        {
            map[i] = Console.ReadLine().ToCharArray();
        }

        if (seconds == 1)
        {
            DumpMap(map);

            return;
        }

        if (seconds % 2 == 0)
        {
            for (int i = 0; i < rows; ++i)
                for (int j = 0; j < columns; ++j)
                    map[i][j] = 'O';

            DumpMap(map);

            return;
        }

        IterateMap(map);

        if (seconds % 4 == 1)
            IterateMap(map);

        DumpMap(map);
    }

    private static void IterateMap(char[][] map)
    {
        // Blow up the bombs
        for (int i = 0; i < map.Length; ++i)
        {
            for (int j = 0; j < map[i].Length; ++j)
            {
                if (map[i][j] == 'O')
                {
                    map[i][j] = ' ';
                    ClearCell(map, i - 1, j);
                    ClearCell(map, i + 1, j);
                    ClearCell(map, i, j - 1);
                    ClearCell(map, i, j + 1);
                }
            }
        }

        for (int i = 0; i < map.Length; ++i)
        {
            for (int j = 0; j < map[i].Length; ++j)
            {
                if (map[i][j] == '.')
                    map[i][j] = 'O';
                else
                    map[i][j] = '.';
            }
        }
    }

    private static void DumpMap(char[][] map)
    {
        for (int i = 0; i < map.Length; ++i)
        {
            Console.Out.WriteLine(String.Join("", map[i]));
        }
    }

    private static void ClearCell(char[][] map,int r,int c)
    {
        if (r < 0) return;
        if (r >= map.Length) return;
        if (c < 0) return;
        if (c >= map[r].Length) return;
        if (map[r][c] == 'O') return;
        map[r][c] = ' ';
    }
}

 

Attempt The Bomberman Game HackerRank Challenge

Link – https://www.hackerrank.com/challenges/bomber-man/

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/emas-supercomputer-hackerrank-solution/

Leave a Comment