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.
classResult{/** * Finds the maximum product of areas of two non-overlapping plus shapes. */publicstaticinttwoPluses(List<String>grid){introws=grid.size();intcols=grid.get(0).length();List<Set<Integer>>pluses=newArrayList<>();char[][]matrix=convertToMatrix(grid);intmaxProduct=0;// Identify all possible plusesfor(intr=0;r<rows;r++){for(intc=0;c<cols;c++){if(matrix[r][c]=='G'){intmaxWingLength=findMaxWing(matrix,r,c);// Find and save all the pluses that shares the same center as smaller pluses might not overlap while bigger ones dofor(inti=maxWingLength;i>=0;i--){pluses.add(getPlusCells(r,c,i,cols));}}}}// Check every pair of pluses. if they don't overlap, compare the product of them with the max product found up to that point.for(inti=0;i<pluses.size();i++){for(intj=i+1;j<pluses.size();j++){if(!hasOverlap(pluses.get(i),pluses.get(j))){intproduct=pluses.get(i).size()*pluses.get(j).size();maxProduct=Math.max(maxProduct,product);}}}returnmaxProduct;}/** * Determines the maximum wing length of a plus centered at the given cell. Checks each direction. */privatestaticintfindMaxWing(char[][]matrix,introw,intcol){introws=matrix.length;intcols=matrix[0].length;intmaxWing=0;while(row-maxWing>=0&&row+maxWing<rows&&col-maxWing>=0&&col+maxWing<cols&&matrix[row-maxWing][col]=='G'&&matrix[row+maxWing][col]=='G'&&matrix[row][col-maxWing]=='G'&&matrix[row][col+maxWing]=='G'){maxWing++;}returnmaxWing-1;}/** * Converts the grid of strings into a 2D character array. */privatestaticchar[][]convertToMatrix(List<String>grid){introws=grid.size();intcols=grid.get(0).length();char[][]matrix=newchar[rows][cols];for(intr=0;r<rows;r++){matrix[r]=grid.get(r).toCharArray();}returnmatrix;}/** * Returns the set of cell indices covered by a plus with the given center and * wing length. */privatestaticSet<Integer>getPlusCells(introw,intcol,intwingLength,intcols){Set<Integer>cells=newHashSet<>();cells.add(row*cols+col);// Center cellfor(inti=1;i<=wingLength;i++){cells.add((row-i)*cols+col);// Upcells.add((row+i)*cols+col);// Downcells.add(row*cols+(col-i));// Leftcells.add(row*cols+(col+i));// Right}returncells;}/** * Checks if two pluses overlap. */privatestaticbooleanhasOverlap(Set<Integer>plus1,Set<Integer>plus2){for(intcell:plus1){if(plus2.contains(cell)){returntrue;}}returnfalse;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Ema's Supercomputer
You are viewing a single comment's thread. Return to all comments →
Solution in java: