We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Java8 solution, just switch between the two states of the grid:
publicstaticList<String>bomberMan(intn,List<String>grid){// Write your code hereif(n==1){returngrid;}if(n%2==0){intlength=grid.get(0).length();StringoString=repeatChar('O',length);for(inti=0;i<grid.size();i++){grid.set(i,oString);}returngrid;}grid=switchStates(grid);if(n%4==3){returngrid;}returnswitchStates(grid);}publicstaticStringrepeatChar(charc,inttimes){StringBuildersb=newStringBuilder(times);for(inti=0;i<times;i++){sb.append(c);}returnsb.toString();}// function to switch between the 2 states -// from seconds 3-7-11-15---n%4==3// to seconds 5-9-13-17---n%4==1publicstaticList<String>switchStates(List<String>grid){char[][]charArray=newchar[grid.size()][];for(inti=0;i<grid.size();i++){charArray[i]=grid.get(i).toCharArray();// Convert each String to a char[]}for(inti=0;i<grid.size();i++){second:for(intj=0;j<charArray[0].length;j++){int[][]positions={{i+1,j},{i-1,j},{i,j+1},{i,j-1}};if(grid.get(i).charAt(j)=='.'){for(int[]pos:positions){intx=pos[0];inty=pos[1];if(x>=0&&x<grid.size()&&y>=0&&y<charArray[0].length){if(grid.get(x).charAt(y)=='O'){continuesecond;}}}charArray[i][j]='O';}else{charArray[i][j]='.';for(int[]pos:positions){intx=pos[0];inty=pos[1];if(x>=0&&x<grid.size()&&y>=0&&y<charArray[0].length){charArray[x][y]='.';}}}}}for(inti=0;i<charArray.length;i++){Strings=newString(charArray[i]);grid.set(i,s);}returngrid;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
The Bomberman Game
You are viewing a single comment's thread. Return to all comments →
Java8 solution, just switch between the two states of the grid: