Hackerrank The Bomberman Game Solution
.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}
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 , any valid cells and 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 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:OOOOOOOOO
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.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}
The first line contains three space-separated integers , , and , The number of rows, columns and seconds to simulate.
Each of the next lines contains a row of the matrix as a single string of characters. The .
character denotes an empty cell, and the O
character (ascii 79) denotes a bomb.
Constraints.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}
Subtask
- for of the maximum score.
Output Format.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}
Print the grid's final state. This means lines where each line contains characters, and each character is either a .
or an O
(ascii 79). This grid must represent the state of the grid after seconds.
Sample Input.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue}
6 7 3
.......
...O...
....O..
.......
OO.....
OO.....
Sample Output.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue}
OOO.OOO
OO...OO
OOO...O
..OO.OO
...OOOO
...OOOO
Explanation.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue}
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
Solution in java8
Approach 1.
import java.util.Scanner;
public class Solution{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Solution sol = new Solution();
String[] st = sc.nextLine().split(" ");
int r = Integer.parseInt(st[0]);
int c = Integer.parseInt(st[1]);
int n = Integer.parseInt(st[2]);
String[] data = new String[r];
String[] gridAt2 = new String[r];
String[] gridAt21 = new String[r];
String[] gridAt22 = new String[r];
String[] gridAt3 = new String[r];
String[] gridAt5 = new String[r];
//int[][] gridAt2 = new int[r][c];
//int[][] gridAt3 = new int[r][c];
//int[][] gridAt5 = new int[r][c];
for(int i=0;i<r;i++) {
data[i] = sc.nextLine();
gridAt2[i]="";
gridAt21[i]="";
gridAt22[i]="";
for(int j=0;j<c;j++) {
gridAt2[i] = gridAt2[i]+'O';
gridAt21[i] = gridAt21[i]+'O';
gridAt22[i] = gridAt22[i]+'O';
}
}
//System.out.println("grid2");
//printGrid(gridAt2,r,c);
gridAt3 = sol.blast(data,gridAt2,r,c);
//System.out.println("grid2");
//printGrid(gridAt2,r,c);
//System.out.println("grid3");
//printGrid(gridAt3,r,c);
gridAt5 = sol.blast(gridAt3,gridAt21,r,c);
//System.out.println("grid5");
//printGrid(gridAt5,r,c);
//System.out.println("ans");
//System.out.println(""+((n-5)%4==0));
if(n==0||n==1) {
printGrid(data,r,c);
}
else if(n%2==0) {
printGrid(gridAt22,r,c);
}
else if((n-3)%4==0) {
printGrid(gridAt3,r,c);
}
else if((n-5)%4==0) {
printGrid(gridAt5,r,c);
}
}
private static void printGrid(String[] d, int r, int c) {
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
System.out.print(""+d[i].charAt(j));
}
System.out.println();
}
}
private String[] blast(String[] d, String[] g,int r,int c) {
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
if(d[i].charAt(j)=='O') {
g[i] = g[i].substring(0,j)+'.'+g[i].substring(j+1);
//System.out.println(""+i+","+j);
if(j+1<c) {
g[i] = g[i].substring(0,j+1)+'.'+g[i].substring(j+2);
}
if(j-1>=0) {
g[i] = g[i].substring(0,j-1)+'.'+g[i].substring(j);
}
if(i+1<r) {
g[i+1] = g[i+1].substring(0,j)+'.'+g[i+1].substring(j+1);
}
if(i-1>=0) {
g[i-1] = g[i-1].substring(0,j)+'.'+g[i-1].substring(j+1);
}
}
//printGrid(g,r,c);
}
}
//System.out.println();
return g;
}
}
Approach 2.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the bomberMan function below.
static String[] bomberMan(int n, String[] grid) {
int f=grid.length;
int c=grid[0].length();
char[][] matrizRes= new char[f][c];
System.out.println(f+"---"+c);
if(n==1)
return grid;
if(n%2==0){
// String[] matrizRes2= new String[f];
for(int i=0;i<f;i++){
grid[i]="";
for(int j=0;j<c;j++){
grid[i]=grid[i].concat("O");
}
}
return grid;
}
// for(int s=3;s<=n;s+=2){
for(int i=0;i<f;i++){
for(int j=0;j<c;j++){
if(cantVecinos(grid,i,j)>0)
matrizRes[i][j]='.';
else
matrizRes[i][j]='O';
}
}
System.out.println("-------------------");
for(int i=0;i<f;i++){
grid[i]=String.valueOf(matrizRes[i]);
System.out.println(grid[i]);
}
if(n%4==3)
return grid;
for(int i=0;i<f;i++){
for(int j=0;j<c;j++){
if(cantVecinos(grid,i,j)>0)
matrizRes[i][j]='.';
else
matrizRes[i][j]='O';
}
}
for(int i=0;i<f;i++){
grid[i]=String.valueOf(matrizRes[i]);
System.out.println(grid[i]);
}
//}
return grid;
}
public static int cantVecinos(String[]grid, int fila, int columna){
if(grid[fila].charAt(columna)=='O')
return 1;
if(fila>0)
if(grid[fila-1].charAt(columna)=='O')
return 1;
if(fila<grid.length-1)
if(grid[fila+1].charAt(columna)=='O')
return 1;
if(columna>0)
if(grid[fila].charAt(columna-1)=='O')
return 1;
if(columna<grid[0].length()-1)
if(grid[fila].charAt(columna+1)=='O')
return 1;
return 0;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] rcn = scanner.nextLine().split(" ");
int r = Integer.parseInt(rcn[0]);
int c = Integer.parseInt(rcn[1]);
int n = Integer.parseInt(rcn[2]);
String[] grid = new String[r];
for (int i = 0; i < r; i++) {
String gridItem = scanner.nextLine();
grid[i] = gridItem;
}
String[] result = bomberMan(n, grid);
for (int i = 0; i < result.length; i++) {
bufferedWriter.write(result[i]);
if (i != result.length - 1) {
bufferedWriter.write("\n");
}
}
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
Approach 3.
import java.io.*;
import java.util.*;
class Cell {
boolean hasBomb;
int timePlaced;
Cell(boolean b, int n) {
hasBomb = b;
timePlaced = n;
}
}
public class Solution {
public static void printGrid(Cell[][] grid) {
for(int i=0;i<grid.length;i++) {
for(int j=0;j<grid[0].length;j++) {
if(grid[i][j].hasBomb) System.out.print("O");
else System.out.print(".");
}
System.out.println();
}
}
public static Cell[][] fillGrid (Cell[][] grid, int turn) {
for(int i=0;i<grid.length;i++) {
for(int j=0;j<grid[0].length;j++) {
if(!grid[i][j].hasBomb) {
grid[i][j].hasBomb=true;
grid[i][j].timePlaced=turn;
}
}
}
return grid;
}
public static Cell[][] blowBombs(Cell[][] grid, int turn) {
for(int i=0;i<grid.length;i++) {
for(int j=0;j<grid[0].length;j++) {
if(grid[i][j].hasBomb) {
if(grid[i][j].timePlaced == turn-3) { // Was this placed 3 turns ago?
if(i-1>=0) {
grid[i-1][j].hasBomb=false;
}
if(j-1>=0) {
grid[i][j-1].hasBomb=false;
}
if(i+1 < grid.length) {
if(!((grid[i+1][j].hasBomb) && (grid[i+1][j].timePlaced==turn-3)))
grid[i+1][j].hasBomb=false;
}
if(j+1 < grid[0].length) {
if(!((grid[i][j+1].hasBomb) && (grid[i][j+1].timePlaced==turn-3)))
grid[i][j+1].hasBomb =false;
}
grid[i][j].hasBomb = false;
}
}
}
}
return grid;
}
public static void doGame(Cell[][] grid, int turns) {
if(turns==1) { // Special case
printGrid(grid);
return;
}
if(turns%2==0) { // Special case
grid = fillGrid(grid, 2); // Populate for turn 2
printGrid(grid);
return;
}
if(turns%4==1) {
grid = fillGrid(grid,2);
grid = blowBombs(grid,3);
grid = fillGrid(grid,4);
grid = blowBombs(grid,5);
printGrid(grid);
return;
}
if(turns%4==3) {
grid = fillGrid(grid,2);
grid = blowBombs(grid,3);
printGrid(grid);
return;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rows = sc.nextInt();
int cols = sc.nextInt();
int turns = sc.nextInt();
sc.nextLine();
Cell[][] grid = new Cell[rows][cols];
for(int i=0;i<rows;i++) {
String s = sc.nextLine();
for(int j=0;j<s.length();j++) {
if(s.charAt(j)=='.') grid[i][j] = new Cell(false,-1);
else grid[i][j] = new Cell (true, 0);
}
}
doGame(grid,turns);
}
}
Solution in python3
Approach 1.
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the bomberMan function below.
def bomberMan(n, grid):
# track the time laps 1 second before explode.
def timeLaps(g):
t = list(map(lambda r:list(map(int,r.replace('O','1').replace('.','2') )),g))
for i in range(len(t)):
for j in range(len(t[i])):
if t[i][j] == 1:
t[i][j] = 3
# up
if i-1 >= 0:
if t[i-1][j] != 3:
t[i-1][j] = 3
# down
if i+1 < len(t):
if t[i+1][j] != 1:
t[i+1][j] = 3
# left
if j-1 >= 0:
if t[i][j-1] != 3:
t[i][j-1] = 3
# right
if j+1 < len(t[i]):
if t[i][j+1] != 1:
t[i][j+1] = 3
elif t[i][j] != 3:
t[i][j] -= 1
_t = list(map(lambda r: ''.join(list(map(str,r))), t))
return list(map(lambda r: r.replace('1','O').replace('3','.'), _t))
if n == 1:
return grid
elif n == 2:
return list(map(lambda row: row.replace('.', 'O'), grid))
else:
if ((n - 1) / 2) % 2 == 1:
return timeLaps(grid)
elif ((n - 1) / 2) % 2 == 0:
temp_grid = timeLaps(grid)
return timeLaps(temp_grid)
else:
return list(map(lambda row: row.replace('.', 'O'), grid))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
rcn = input().split()
r = int(rcn[0])
c = int(rcn[1])
n = int(rcn[2])
grid = []
for _ in range(r):
grid_item = input()
grid.append(grid_item)
result = bomberMan(n, grid)
fptr.write('\n'.join(result))
fptr.write('\n')
fptr.close()
Approach 2.
import sys
"""
Since detonations take place only at odd times, if n (the number of seconds) is even,
the grid is composed only of O.
At n == 1, no detonations take place, so the grid is the starting grid (initial_grid).
At n == 3, the first detonation happens (grid_after_first_detonation).
After this second, we note that there is a recurrent pattern that repeat itself every 4 seconds:
- at n == 5, 9, 13, ... (i.e. when n % 4 == 1), the grid is equal to grid_after_second_detonation
- at n == 7, 11, 15, ... (i.e when n % 4 == 3), the grid is equal to grid_after_third_detonation
"""
def createGrid(r, c, grid_at_previous_step):
grid_at_next_step = [['O'] * c for _ in range(r)]
for i in range(r):
for j in range(c):
current_cell = grid_at_previous_step[i][j]
if current_cell == 'O':
grid_at_next_step[i][j] = '.'
if i - 1 >= 0:
grid_at_next_step[i - 1][j] = '.'
if i + 1 <= r - 1:
grid_at_next_step[i + 1][j] = '.'
if j - 1 >= 0:
grid_at_next_step[i][j - 1] = '.'
if j + 1 <= c - 1:
grid_at_next_step[i][j + 1] = '.'
return grid_at_next_step
def bomberMan(n, r, c, initial_grid):
grid_after_first_detonation = createGrid(r, c, initial_grid)
if n % 2 == 0:
return [['O'] * c for _ in range(r)]
elif n < 4:
return initial_grid if n == 1 else grid_after_first_detonation
else:
grid_after_second_detonation = createGrid(r, c, grid_after_first_detonation)
grid_after_third_detonation = createGrid(r, c, grid_after_second_detonation)
return grid_after_second_detonation if n % 4 == 1 else grid_after_third_detonation
if __name__ == "__main__":
r, c, n = input().strip().split(' ')
r, c, n = [int(r), int(c), int(n)]
grid = []
for _ in range(r):
grid.append(list(str(input().strip())))
result = bomberMan(n, r, c, grid)
for row in result:
print("".join(row))
Approach 3.
import sys
#!/bin/python3
import sys
"""
Since detonations take place only at odd times, if n (the number of seconds) is even,
the grid is composed only of O.
At n == 1, no detonations take place, so the grid is the starting grid (initial_grid).
At n == 3, the first detonation happens (grid_after_first_detonation).
After this second, we note that there is a recurrent pattern that repeat itself every 4 seconds:
- at n == 5, 9, 13, ... (i.e. when n % 4 == 1), the grid is equal to grid_after_second_detonation
- at n == 7, 11, 15, ... (i.e when n % 4 == 3), the grid is equal to grid_after_third_detonation
"""
def createGrid(r, c, grid_at_previous_step):
grid_at_next_step = [['O'] * c for _ in range(r)]
for i in range(r):
for j in range(c):
current_cell = grid_at_previous_step[i][j]
if current_cell == 'O':
grid_at_next_step[i][j] = '.'
if i - 1 >= 0:
grid_at_next_step[i - 1][j] = '.'
if i + 1 <= r - 1:
grid_at_next_step[i + 1][j] = '.'
if j - 1 >= 0:
grid_at_next_step[i][j - 1] = '.'
if j + 1 <= c - 1:
grid_at_next_step[i][j + 1] = '.'
return grid_at_next_step
def bomberMan(n, r, c, initial_grid):
grid_after_first_detonation = createGrid(r, c, initial_grid)
if n % 2 == 0:
return [['O'] * c for _ in range(r)]
elif n < 4:
return initial_grid if n == 1 else grid_after_first_detonation
else:
grid_after_second_detonation = createGrid(r, c, grid_after_first_detonation)
grid_after_third_detonation = createGrid(r, c, grid_after_second_detonation)
return grid_after_second_detonation if n % 4 == 1 else grid_after_third_detonation
if __name__ == "__main__":
r, c, n = input().strip().split(' ')
r, c, n = [int(r), int(c), int(n)]
grid = []
for _ in range(r):
grid.append(list(str(input().strip())))
result = bomberMan(n, r, c, grid)
for row in result:
print("".join(row))
Solution in cpp
Approach 1.
#include<bits/stdc++.h>
using namespace std;
int main()
{
//int t;
//cin>>t;
//while(t--){
int r,c,n,i,j,x,y,p,q,C;
cin>>r>>c>>n;
char s[r][c];
vector<pair<int,int> >v;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cin>>s[i][j];
if(s[i][j]=='O')
{
v.push_back(make_pair(i,j));
}
}
}
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
for(C=2;C<=n;C++)
{
if(C%2==0)
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
s[i][j]='O';
}
}
if(n%2==0)
{
break;
}
}
if((C-1)%2==0)
{
for(i=0;i<v.size();i++)
{
x=v[i].first;
y=v[i].second;
s[x][y]='.';
for(j=0;j<4;j++)
{
p=x+dx[j];
q=y+dy[j];
if(p>=0&&p<=r-1&&q>=0&&q<=c-1)
{
s[p][q]='.';
}
}
}
if((n+1)%4==0)
{
break;
}
if(C>=5){
if((n-1)%4==0)
{
break;
}
}
v.clear();
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(s[i][j]=='O')
{
v.push_back(make_pair(i,j));
}
}
}
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cout<<s[i][j];
}
cout<<endl;
}
//}
return 0;
}
Approach 2.
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the bomberMan function below.
vector<string> bomberMan(int n, vector<string> grid) {
vector<string>s=grid,s1,s2;
for(int i=0;i<grid.size();i++)
for (int j=0;j<grid[0].size();j++)
s[i][j]='O';
s1=s2=s;
for(int i=0;i<grid.size();i++)
for(int j=0;j<grid[0].size();j++)
if(grid[i][j]=='O'){
s1[i][j]='.';
if(i>0) s1[i-1][j]='.';
if(i<grid.size()-1) s1[i+1][j]='.';
if(j>0) s1[i][j-1]='.';
if(j<grid[0].size()-1) s1[i][j+1]='.';
}
for(int i=0;i<grid.size();i++)
for(int j=0;j<grid[0].size();j++){
if(s1[i][j]=='O'){
s2[i][j]='.';
if(i>0) s2[i-1][j]='.';
if(i<s1.size()-1) s2[i+1][j]='.';
if(j>0) s2[i][j-1]='.';
if(j<s1[0].size()-1) s2[i][j+1]='.';
}
}
if(n%2==0)
return s;
if(n==1)
return grid;
if(n%4==3)
return s1;
return s2;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string rcn_temp;
getline(cin, rcn_temp);
vector<string> rcn = split_string(rcn_temp);
int r = stoi(rcn[0]);
int c = stoi(rcn[1]);
int n = stoi(rcn[2]);
vector<string> grid(r);
for (int i = 0; i < r; i++) {
string grid_item;
getline(cin, grid_item);
grid[i] = grid_item;
}
vector<string> result = bomberMan(n, grid);
for (int i = 0; i < result.size(); i++) {
fout << result[i];
if (i != result.size() - 1) {
fout << "\n";
}
}
fout << "\n";
fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
Approach 3.
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the bomberMan function below.
vector<string> op(vector<string>&v,int z){
int n=v.size(),m=v[0].size();
string p;
vector<string>ans;
for(int i=0;i<m;i++)p+='O';
for(int i=0;i<n;i++)ans.push_back(p);
if(z)return ans;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(v[i][j]=='O')ans[i][j]='.';
else if(i>0&&v[i-1][j]=='O')ans[i][j]='.';
else if(j>0&&v[i][j-1]=='O')ans[i][j]='.';
else if(i<n-1&&v[i+1][j]=='O')ans[i][j]='.';
else if(j<m-1&&v[i][j+1]=='O')ans[i][j]='.';
}
}
return ans;
}
vector<string>a,b;
vector<string> bomberMan(int n, vector<string> grid) {
int i=1;
if(n==i)return grid;i++;
if(n==i)return op(grid,1);i++;
grid=op(grid,0);
if(n==i)return grid;i++;
if(n==i)return op(grid,1);i++;
if(n==i)return op(grid,0);
if(n%2==0)return op(grid,1);
if((n/2)%2==0)return op(grid,0);
return grid;
//1-0 2-f 3-r 4-f 5-o 6-f 7-r 8-f 9-o 10-f 11-r
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string rcn_temp;
getline(cin, rcn_temp);
vector<string> rcn = split_string(rcn_temp);
int r = stoi(rcn[0]);
int c = stoi(rcn[1]);
int n = stoi(rcn[2]);
vector<string> grid(r);
for (int i = 0; i < r; i++) {
string grid_item;
getline(cin, grid_item);
grid[i] = grid_item;
}
vector<string> result = bomberMan(n, grid);
for (int i = 0; i < result.size(); i++) {
fout << result[i];
if (i != result.size() - 1) {
fout << "\n";
}
}
fout << "\n";
fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}