|
| 1 | +/** |
| 2 | + * 1274. Number of Ships in a Rectangle |
| 3 | + * https://leetcode.com/problems/number-of-ships-in-a-rectangle/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Each ship is located at an integer point on the sea represented by a cartesian plane, and |
| 7 | + * each integer point may contain at most 1 ship. |
| 8 | + * |
| 9 | + * You have a function Sea.hasShips(topRight, bottomLeft) which takes two points as arguments |
| 10 | + * and returns true If there is at least one ship in the rectangle represented by the two |
| 11 | + * points, including on the boundary. |
| 12 | + * |
| 13 | + * Given two points: the top right and bottom left corners of a rectangle, return the number |
| 14 | + * of ships present in that rectangle. It is guaranteed that there are at most 10 ships in |
| 15 | + * that rectangle. |
| 16 | + * |
| 17 | + * Submissions making more than 400 calls to hasShips will be judged Wrong Answer. Also, any |
| 18 | + * solutions that attempt to circumvent the judge will result in disqualification. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {Sea} sea |
| 23 | + * @param {integer[]} topRight |
| 24 | + * @param {integer[]} bottomLeft |
| 25 | + * @return {integer} |
| 26 | + */ |
| 27 | +var countShips = function(sea, topRight, bottomLeft) { |
| 28 | + const [x2, y2] = topRight; |
| 29 | + const [x1, y1] = bottomLeft; |
| 30 | + |
| 31 | + if (x1 > x2 || y1 > y2 || !sea.hasShips(topRight, bottomLeft)) { |
| 32 | + return 0; |
| 33 | + } |
| 34 | + |
| 35 | + if (x1 === x2 && y1 === y2) { |
| 36 | + return 1; |
| 37 | + } |
| 38 | + |
| 39 | + const midX = Math.floor((x1 + x2) / 2); |
| 40 | + const midY = Math.floor((y1 + y2) / 2); |
| 41 | + |
| 42 | + return countShips(sea, [midX, midY], [x1, y1]) |
| 43 | + + countShips(sea, [x2, midY], [midX + 1, y1]) |
| 44 | + + countShips(sea, [midX, y2], [x1, midY + 1]) |
| 45 | + + countShips(sea, [x2, y2], [midX + 1, midY + 1]); |
| 46 | +}; |
0 commit comments