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

    My Java solution with linear time and o(k) space complexity:

    static Map<Integer, Set<Integer>> obstacleMap = new HashMap<>();
    
    public static int queensAttack(int n, int k, int r_q, int c_q, List<List<Integer>> obstacles) {
        // Clear the map in case the method is called multiple times
        obstacleMap.clear();
        
        // Populate the map
        for (List<Integer> obstacle : obstacles) {
            int r = obstacle.get(0), c = obstacle.get(1);
            obstacleMap.computeIfAbsent(r, x -> new HashSet<>()).add(c);
        }
    
        // Count all directions
        int total = 0;
        total += countDirection(n, r_q, c_q, -1, 0);  // up
        total += countDirection(n, r_q, c_q, 1, 0);   // down
        total += countDirection(n, r_q, c_q, 0, -1);  // left
        total += countDirection(n, r_q, c_q, 0, 1);   // right
        total += countDirection(n, r_q, c_q, -1, -1); // up-left
        total += countDirection(n, r_q, c_q, -1, 1);  // up-right
        total += countDirection(n, r_q, c_q, 1, -1);  // down-left
        total += countDirection(n, r_q, c_q, 1, 1);   // down-right
    
        return total;
    }
    
    // Generic method to count squares in one direction
    public static int countDirection(int n, int r, int c, int dr, int dc) {
        int count = 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;
        }
        return count;
    }