1274 numbers of ships in a rectangle

https://leetcode.com/problems/number-of-ships-in-a-rectangle/description/

boring,不过要注意不要在进下一层dfs之前就各种判断,所有判断都是进来之后在当前这一层做的

/**
 * // This is Sea's API interface.
 * // You should not implement it, or speculate about its implementation
 * class Sea {
 *     public boolean hasShips(int[] topRight, int[] bottomLeft);
 * }
 */

class Solution {
    public int countShips(Sea sea, int[] topRight, int[] bottomLeft) {
        if (bottomLeft[0] > topRight[0] && bottomLeft[1] > topRight[1]) {
            return 0;
        }
        if (bottomLeft[0] == topRight[0] && bottomLeft[1] == topRight[1]) {
            return sea.hasShips(topRight, bottomLeft) ? 1 : 0;
        }
        if (!sea.hasShips(topRight, bottomLeft)) return 0;
        int wmid = (bottomLeft[0] + topRight[0]) / 2;
        int hmid = (bottomLeft[1] + topRight[1]) / 2;
        int total = 0;
        
        total += countShips(sea, new int[]{wmid, hmid}, bottomLeft);
        total += countShips(sea, topRight, new int[]{wmid + 1, hmid + 1});
        total += countShips(sea, new int[]{wmid, topRight[1]}, new int[]{bottomLeft[0], hmid + 1});
        total += countShips(sea, new int[]{topRight[0], hmid}, new int[]{wmid + 1, bottomLeft[1]});
        return total;
    }
}

Last updated