Queen's Attack II Discussions | Algorithms | HackerRank
  • + 2 comments

    Java 8, But has a lot of memory. I was trying to recycle this in a future Java project that creates a chess game. It failed only three test cases because of time limit.

    public static int queensAttack(int n, int k, int r_q, int c_q, List<List<Integer>> obstacles) {
            int moves = 0;
            Point queenCord = new Point(c_q, r_q);
            List<Point> list = new ArrayList<>();
            //Creating the list of points representing ordered cordinates of obstacles
            //and adding it to list 
            for(List<Integer> l : obstacles){
                Point p = new Point(l.get(1),l.get(0));
                list.add(p);
            }
            Point left = new Point(c_q-1,r_q);
            Point right = new Point(c_q+1,r_q);
            Point top = new Point(c_q,r_q+1);
            Point bottom = new Point(c_q,r_q-1);
            Point nE = new Point(c_q+1,r_q+1);
            Point nW = new Point(c_q-1,r_q+1);
            Point sW = new Point(c_q-1,r_q-1);
            Point sE = new Point(c_q+1,r_q-1);
            while(left.getX() != 0 && !list.contains(left)){
                moves++;
                left.translate(-1, 0);
            }
            while(right.getX() != n+1 && !list.contains(right)){
                moves++;
                right.translate(1, 0);
            }
            while(top.getY() != n+1 && !list.contains(top)){
                moves++;
                top.translate(0, 1);
            }
            while(bottom.getY() != 0 && !list.contains(bottom)){
                moves++;
                bottom.translate(0,-1);
            }
            while(nE.getY() != n+1 && nE.getX() != n+1 && !list.contains(nE)){
                moves++;
                nE.translate(1, 1);
            }
            while(nW.getY() != n+1 && nW.getX() != 0 && !list.contains(nW)){
                moves++;
                nW.translate(-1, 1);
            }
            while(sW.getY() != 0 && sW.getX() != 0 && !list.contains(sW)){
                moves++;
                sW.translate(-1, -1);
            }
            while(sE.getY() != 0 && sE.getX()!=n+1 && !list.contains(sE)){
                moves++;
                sE.translate(1, -1);
            }
            return moves;
        }