[LeetCode] Number of Ships in a Rectangle

1274. Number of Ships in a Rectangle

(This problem is an interactive problem.)

Each ship is located at an integer point on the sea represented by a cartesian plane, and each integer point may contain at most 1 ship.

You have a function Sea.hasShips(topRight, bottomLeft) which takes two points as arguments and returns true If there is at least one ship in the rectangle represented by the two points, including on the boundary.

Given two points: the top right and bottom left corners of a rectangle, return the number of ships present in that rectangle. It is guaranteed that there are at most 10 ships in that rectangle.

Submissions making more than 400 calls to hasShips will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

  • Time : O(logn + logm)
  • Space : O(logn + logm)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int countShips(Sea sea, vector<int> topRight, vector<int> bottomLeft) {
if(!sea.hasShips(topRight, bottomLeft)) return 0;
int h = topRight[0] - bottomLeft[0];
int w = topRight[1] - bottomLeft[1];
if(!h and !w) {
return 1;
}
if(h > w) {
if(h/2 == 0) {
return countShips(sea, {bottomLeft[0], topRight[1]}, {bottomLeft[0], bottomLeft[1]})
+ countShips(sea, {topRight[0], topRight[1]}, {topRight[0], bottomLeft[1]});
}else return countShips(sea, {topRight[0] - (h/2), topRight[1]}, {bottomLeft[0], bottomLeft[1]})
+ countShips(sea, {topRight[0], topRight[1]}, {topRight[0] - (h/2) + 1, bottomLeft[1]});
} else {
if(w/2 == 0) {
return countShips(sea, {topRight[0], bottomLeft[1]}, {bottomLeft[0], bottomLeft[1]})
+ countShips(sea, {topRight[0], topRight[1]}, {bottomLeft[0], topRight[1]});
} else return countShips(sea, {topRight[0], topRight[1] - (w/2)}, {bottomLeft[0], bottomLeft[1]})
+ countShips(sea, {topRight[0], topRight[1]}, {bottomLeft[0], topRight[1] - (w/2) + 1});
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/12/PS/LeetCode/number-of-ships-in-a-rectangle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.