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.
My solution in Java. Unfortunately, it's not fast enough and it times out for the most use cases. But at least it's easy to understand :)
classResult{/* * Complete the 'queensBoard' function below. * * The function is expected to return an INTEGER. * The function accepts STRING_ARRAY board as parameter. */publicstaticintqueensBoard(List<String>board){// Write your code hereintN=board.size();intM=board.get(0).length();Map<Integer,Set<Integer>>conflicts=newHashMap<>();for(intn=0;n<N;n++){for(intm=0;m<M;m++){if(board.get(n).charAt(m)=='.'){intcellId=calcCellId(M,n,m);conflicts.put(cellId,findConflictingCells(board,n,m));}}}Set<Integer>emptyCells=newHashSet<>();for(intn=0;n<N;n++){for(intm=0;m<M;m++){if(board.get(n).charAt(m)=='.'){emptyCells.add(calcCellId(M,n,m));}}}Map<Set<Integer>,Integer>dp=newHashMap<>();returncountCombinations(dp,emptyCells,conflicts,emptyCells.size(),0);}publicstaticintcalcCellId(intM,intn,intm){returnM*n+m;}publicstaticSet<Integer>findConflictingCells(List<String>board,intn,intm){Set<Integer>conflictingCells=newHashSet<>();intN=board.size();intM=board.get(0).length();for(intdn=-1;dn<=1;dn++){for(intdm=-1;dm<=1;dm++){if(dn==0&&dm==0){continue;}for(inti=n+dn,j=m+dm;i>=0&&i<N&&j>=0&&j<M;i+=dn,j+=dm){if(board.get(i).charAt(j)=='#'){break;}conflictingCells.add(calcCellId(M,i,j));}}}returnconflictingCells;}publicstaticintcountCombinations(Map<Set<Integer>,Integer>dp,Set<Integer>emptyCells,Map<Integer,Set<Integer>>conflicts,intmaxLevel,intlevel){if(level==maxLevel-1){returnemptyCells.size();}elseif(dp.containsKey(emptyCells)){returndp.get(emptyCells);}else{intcount=emptyCells.size();Set<Integer>localEmptyCells=newHashSet<>(emptyCells);for(IntegercellId:emptyCells){localEmptyCells.remove(cellId);Set<Integer>copyOfEmptyCells=newHashSet<>(localEmptyCells);copyOfEmptyCells.removeAll(conflicts.get(cellId));if(copyOfEmptyCells.size()>0){count+=countCombinations(dp,copyOfEmptyCells,conflicts,maxLevel,level+1);count%=1000_000_007;}}dp.put(emptyCells,count);returncount;}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Queens on Board
You are viewing a single comment's thread. Return to all comments →
My solution in Java. Unfortunately, it's not fast enough and it times out for the most use cases. But at least it's easy to understand :)