⚡Flashcard Drill➔
NeetCode #173LC-1274HardArrays & Hashing
← Back to All Problems

#173 · #1274 · Number of Ships in a Rectangle(矩形内船只的数目)

📌 Problem Statement & Constraints

This is an interactive problem. A Sea object has a hasShips(topRight, bottomLeft) method returning whether any ship exists in the given axis-aligned rectangle (inclusive). Given the rectangle bounds, return the total number of ships. Constraints: 0 <= ships <= 10, coordinates are up to 1000 x 1000, and hasShips may be called at most 400 times.

💡 Core Algorithmic Approaches

  1. This is a divide-and-conquer search: if a rectangle contains no ships, return 0 without recursing.
  2. If the rectangle is a single cell and contains a ship, return 1.
  3. Otherwise split the rectangle into four quadrants at the midpoint and recurse into each.
  4. The hasShips pruning is what keeps the query count low: empty regions cost exactly one call and are never subdivided.

💻 Benchmark Python3 Implementation

class Solution:
    def countShips(self, sea: "Sea", topRight: List[int], bottomLeft: List[int]) -> int:
        x1, y1 = bottomLeft
        x2, y2 = topRight
        if x1 > x2 or y1 > y2:
            return 0
        if not sea.hasShips(topRight, bottomLeft):   # prune empty regions
            return 0
        if x1 == x2 and y1 == y2:
            return 1                                # single cell with a ship
        mx = (x1 + x2) // 2
        my = (y1 + y2) // 2
        # four quadrants
        return (self.countShips(sea, [mx, my], [x1, y1])
                + self.countShips(sea, [mx, y2], [x1, my + 1])
                + self.countShips(sea, [x2, my], [mx + 1, y1])
                + self.countShips(sea, [x2, y2], [mx + 1, my + 1]))

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(ships * log(max coordinate)) in practice: each quadrant that contains ships is subdivided, while empty quadrants are pruned in one call.
💾 Space Complexity
O(log(max coordinate)) for the recursion stack.

⚠️ Interview Pitfalls & Follow-ups

  • Splitting without the hasShips prune: the recursion would explore the entire grid, exceeding the query limit.
  • Getting the quadrant boundaries wrong: the split must be disjoint and cover the whole rectangle, hence mx/mx + 1 and my/my + 1.
  • Forgetting the base case for a single cell: without it, the recursion would split a 1x1 rectangle forever.
  • Using hasShips on a rectangle with reversed corners: the arguments must be ordered as (topRight, bottomLeft).
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

矩形内船只的数目

(此题是 交互式问题 )在二维平面上有一个矩形海域,其中有一些船。每艘船都占据一个格子,且船只之间不相邻(不相交、不接触,包括对角线方向)。给你矩形的右上角坐标 topRight 和左下角坐标 bottomLeft ,返回该矩形内 船 的数目。你可以调用 API Sea.hasShips(topRight, bottomLeft) 判断指定矩形内是否有船,该 API 返回 true/false。约束:0 ≤ bottomLeft[0] &lt; topRight[0] ≤ 1000;0 ≤ bottomLeft[1] &lt; topRight[1] ≤ 1000;最多调用 400 次 hasShips。

核心要点

  • 四叉树分治(标准解) :把当前矩形递归地一分为四,对每个子矩形先调用 hasShips 判断是否有船,若没有则直接剪枝返回 0。
  • 单点判定 :当矩形退化成一个点( topRight == bottomLeft )且 hasShips 返回 true 时,该点就是一艘船,返回 1。
  • 为什么能控制在 400 次调用内 :因为船之间不相邻,任何足够小的子矩形最多包含一艘船,剪枝非常高效。
  • 分割方式 :取中点 mx = (tr[0] + bl[0]) // 2 、 my = (tr[1] + bl[1]) // 2 ,四个子矩形分别为:① bl=(bl0, bl1), tr=(mx, my);② bl=(mx+1, bl1), tr=(tr0, my);③ bl=(bl0, my+1), tr=(mx, tr1);④ bl=(mx+1, my+1), tr=(tr0, tr1)。

常见陷阱

  • 对每个子矩形都递归而不先剪枝 :会导致 hasShips 调用次数爆炸。必须先判断 hasShips 为 false 就返回 0。
  • 分割时的区间边界写错 :必须保证四个子矩形 不重叠且完整覆盖 原矩形。中点 mx 属于左下侧,因此右半的起点是 mx + 1 。
  • 忘记处理空区间 :当矩形宽度或高度为 1 时,分割会产生 bl[0] &gt; tr[0] 的非法矩形,必须提前返回 0。
  • 递归终止条件写成「矩形面积为 1」 :应写成「退化为单点」,即 tr[0] == bl[0] and tr[1] == bl[1] 。
  • 利用「船不相邻」的性质做过度假设 :该性质保证了剪枝效率,但代码本身不需要显式利用它——只需标准四叉树分治即可。

参考实现

class Solution:
    def countShips(self, sea: 'Sea', topRight: tuple, bottomLeft: tuple) -> int:
        def solve(tr, bl) -> int:
            # 非法矩形(分割产生的空区间)
            if bl[0] > tr[0] or bl[1] > tr[1]:
                return 0
            if not sea.hasShips(tr, bl):        # 剪枝:该矩形内无船
                return 0
            if tr[0] == bl[0] and tr[1] == bl[1]:
                return 1                        # 退化为单点且确认有船
            mx = (tr[0] + bl[0]) // 2
            my = (tr[1] + bl[1]) // 2
            return (solve((mx, my), bl)                     # 左下
                    + solve((tr[0], my), (mx + 1, bl[1]))   # 右下
                    + solve((mx, tr[1]), (bl[0], my + 1))   # 左上
                    + solve(tr, (mx + 1, my + 1)))          # 右上

        return solve(topRight, bottomLeft)