Queen's Attack II Discussions | Algorithms | HackerRank
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 Java solution with linear time and o(k) space complexity:
staticMap<Integer,Set<Integer>>obstacleMap=newHashMap<>();publicstaticintqueensAttack(intn,intk,intr_q,intc_q,List<List<Integer>>obstacles){// Clear the map in case the method is called multiple timesobstacleMap.clear();// Populate the mapfor(List<Integer>obstacle:obstacles){intr=obstacle.get(0),c=obstacle.get(1);obstacleMap.computeIfAbsent(r,x->newHashSet<>()).add(c);}// Count all directionsinttotal=0;total+=countDirection(n,r_q,c_q,-1,0);// uptotal+=countDirection(n,r_q,c_q,1,0);// downtotal+=countDirection(n,r_q,c_q,0,-1);// lefttotal+=countDirection(n,r_q,c_q,0,1);// righttotal+=countDirection(n,r_q,c_q,-1,-1);// up-lefttotal+=countDirection(n,r_q,c_q,-1,1);// up-righttotal+=countDirection(n,r_q,c_q,1,-1);// down-lefttotal+=countDirection(n,r_q,c_q,1,1);// down-rightreturntotal;}// Generic method to count squares in one directionpublicstaticintcountDirection(intn,intr,intc,intdr,intdc){intcount=0;r+=dr;c+=dc;while(r>=1&&r<=n&&c>=1&&c<=n){if(obstacleMap.containsKey(r)&&obstacleMap.get(r).contains(c))break;count++;r+=dr;c+=dc;}returncount;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Queen's Attack II
You are viewing a single comment's thread. Return to all comments →
My Java solution with linear time and o(k) space complexity: