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.
publicstaticList<String>bomberMan(intn,List<String>grid){// Write your code hereinth=grid.size();intl=grid.get(0).length();Map<String,Boolean>blownUpPositions=newHashMap<>();char[][]gridArray=gridArray(grid);Map<String,Boolean>bombPositions=getBombsPositions(gridArray,blownUpPositions);if(n==1)returngrid;if(n%2==0)returnplacedBombGridList(h,l);if(n%4==1){for(inti=0;i<2;i++){bombPositions=flip(gridArray,bombPositions,blownUpPositions,h,l);}}else{bombPositions=flip(gridArray,bombPositions,blownUpPositions,h,l);}returnnewGrid(h,l,bombPositions);}privatestaticMap<String,Boolean>flip(char[][]gridArray,Map<String,Boolean>bombPositions,Map<String,Boolean>blownUpPositions,inth,intl){gridArray=placeBombsGrid(h,l);blownUpPositions=getBlownUpPostions(bombPositions,h,l);returngetBombsPositions(gridArray,blownUpPositions);}privatestaticMap<String,Boolean>getBlownUpPostions(Map<String,Boolean>bombPositons,inth,intl){Map<String,Boolean>blownUpPostions=newHashMap<>();bombPositons.forEach((k,v)->{String[]bps=k.split(",");intx=Integer.parseInt(bps[0]);inty=Integer.parseInt(bps[1]);blownUpPostions.put(k,true);if(x-1>=0)blownUpPostions.put((x-1)+","+y,true);if(x+1<h)blownUpPostions.put((x+1)+","+y,true);if(y-1>=0)blownUpPostions.put(x+","+(y-1),true);if(y+1<l)blownUpPostions.put(x+","+(y+1),true);});returnblownUpPostions;}privatestaticMap<String,Boolean>getBombsPositions(char[][]grid,Map<String,Boolean>blownUpPostions){Map<String,Boolean>bombPostions=newHashMap<>();inth=grid.length;intl=grid[0].length;for(inti=0;i<h;i++){for(intj=0;j<l;j++){Stringpostion=i+","+j;if(grid[i][j]=='O'&&blownUpPostions.get(postion)==null){bombPostions.put(postion,true);}}}returnbombPostions;}privatestaticchar[][]placeBombsGrid(inth,intl){char[][]gridArray=newchar[h][l];for(inti=0;i<h;i++){for(intj=0;j<l;j++){gridArray[i][j]='O';}}returngridArray;}privatestaticList<String>placedBombGridList(inth,intl){List<String>grid=newArrayList<>();for(inti=0;i<h;i++){StringBuilderx=newStringBuilder();for(intj=0;j<l;j++){x.append("O");}grid.add(x.toString());}returngrid;}privatestaticList<String>newGrid(inth,intl,Map<String,Boolean>bombPositions){List<String>grid=newArrayList<>();for(inti=0;i<h;i++){StringBuilderx=newStringBuilder();for(intj=0;j<l;j++){Stringpostion=i+","+j;x.append((bombPositions.get(postion)!=null)?"O":".");}grid.add(x.toString());}returngrid;}privatestaticchar[][]gridArray(List<String>grid){inth=grid.size();intl=grid.get(0).length();char[][]gridArray=newchar[h][l];inti=0;for(Stringrow:grid){gridArray[i]=row.toCharArray();i++;}returngridArray;}
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 →
Java