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

    def queensAttack(n, k, r_q, c_q, obstacles): # Create a set of obstacle positions obstacles = set(tuple(obstacle) for obstacle in obstacles)

    # Directions for the queen's movements
    directions = [
        (1, 0),   # Down
        (-1, 0),  # Up
        (0, 1),   # Right
        (0, -1),  # Left
        (1, 1),   # Down-Right
        (1, -1),  # Down-Left
        (-1, 1),  # Up-Right
        (-1, -1)  # Up-Left
    ]
    
    total = 0
    
    for dx, dy in directions:
        x, y = r_q, c_q
    
        # Initialize the maximum reachable distance in this direction
        max_distance = n  # maximum distance to the edge of the board
    
        while True:
            x += dx
            y += dy
    
            # Check if the new position is within the board limits
            if not (1 <= x <= n and 1 <= y <= n):
                break
    
            # Check if there's an obstacle
            if (x, y) in obstacles:
                break
    
            total += 1  # Increment the count of positions the queen can attack
    
    return total