470. Number of Ships in a Rectangle
You are given two points on a 2D Cartesian plane:
- bottomLeft = [x1, y1]
- topRight = [x2, y2]
These two points define a rectangle whose sides are parallel to the axes.
Each ship is placed at an integer coordinate on the plane, and no two ships share the same point.
You do not know the locations of the ships directly. Instead, you can only use the following API:
- bool hasShips(Point topRight, Point bottomLeft)
This function returns:
- true if there is at least one ship inside or on the boundary of the rectangle formed by topRight and bottomLeft
- false otherwise
Your task is to return the number of ships present inside the given rectangle.
It is guaranteed that there are at most 10 ships inside the rectangle.
A solution that makes more than 400 calls to hasShips will be judged as Wrong Answer.
The list of ship positions is provided only for explaining the examples or initializing the hidden judge. Your solution must work without accessing ship coordinates directly. You must solve the problem only by using the hasShips API.
Example 1:
Input: ships = [[1,1],[2,3],[4,4],[6,2]], topRight = [4,4], bottomLeft = [1,1]
Output: 3
Explanation:
- The rectangle covers all points from [1,1] to [4,4], including the boundary.
- The ships at [1,1], [2,3], and [4,4] lie inside this rectangle.
- The ship at [6,2] lies outside the rectangle.
- So, the answer is 3.
Example 2:
Input: ships = [[0,0],[2,1],[3,2],[7,7]], topRight = [3,2], bottomLeft = [0,0]
Output: 3
Explanation:
- The rectangle includes all integer points from [0,0] to [3,2].
- The ships at [0,0], [2,1], and [3,2] are inside the rectangle.
- The ship at [7,7] is outside.
- So, the total number of ships in the rectangle is 3.
Now Your Turn!
Pick the correct output for the given inputInput: ships = [[1,2],[2,2],[2,3],[4,4]], topRight = [2,3], bottomLeft = [1,2]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 0 <= bottomLeft[0] <= topRight[0] <= 1000
- 0 <= bottomLeft[1] <= topRight[1] <= 1000
- topRight != bottomLeft
- Each ship is located at an integer point
- Each integer point contains at most one ship
- There are at most 10 ships in the given rectangle
- You must solve the problem using only the hasShips API
- More than 400 calls to hasShips will result in Wrong Answer