public int CountShips(Sea sea, int[] topRight, int[] bottomLeft)
        {
            // Divide and Conquer.
            if (!sea.HasShips(topRight, bottomLeft))
            {
                return(0);
            }
            if (topRight[0] == bottomLeft[0] && topRight[1] == bottomLeft[1])
            {
                return(1);
            }

            if (topRight[0] > bottomLeft[0])
            {
                // Divide into left and right parts.
                int mid   = bottomLeft[0] + (topRight[0] - bottomLeft[0]) / 2;
                int left  = CountShips(sea, new int[] { mid, topRight[1] }, bottomLeft);
                int right = CountShips(sea, topRight, new int[] { mid + 1, bottomLeft[1] });
                return(left + right);
            }
            else
            {
                // Divide into bottom and top parts.
                int mid    = bottomLeft[1] + (topRight[1] - bottomLeft[1]) / 2;
                int bottom = CountShips(sea, new int[] { topRight[0], mid }, bottomLeft);
                int top    = CountShips(sea, topRight, new int[] { bottomLeft[0], mid + 1 });
                return(bottom + top);
            }
        }
示例#2
0
    public int CountShips(Sea sea, int[] rt, int[] lb)
    {
        int l = lb[0];
        int b = lb[1];
        int r = rt[0];
        int t = rt[1];

        if (!sea.HasShips(rt, lb))
        {
            return(0);
        }
        if (l == r && b == t)
        {
            return(1);
        }

        int x = l + (r - l) / 2;
        int y = b + (t - b) / 2;

        return
            (CountShips(sea, new int[] { r, t }, new int[] { x + 1, y + 1 }) +
             CountShips(sea, new int[] { x, t }, new int[] { l, y + 1 }) +
             CountShips(sea, new int[] { x, y }, new int[] { l, b }) +
             CountShips(sea, new int[] { r, y }, new int[] { x + 1, b }));
    }