给定一个 N*M 的网格,打印其中的矩形数量。
示例:
输入: N = 2,M = 2
输出: 9
有 4 个大小为 1 x 1 的矩形。
有 2 个大小为 1 x 2 的矩形
有 2 个大小为 2 x 1 的矩形
有一个大小为 2 x 2 的矩形。
输入: N = 5,M = 4
输出: 150
输入: N = 4,M = 3
输出: 60
强力破解方法:
迭代所有可能的水平线对。
迭代所有可能的垂直线对。
计算一下可以用这些线形成的矩形的数量。
以下是上述方法的代码:
def rect_count(n, m):
count = 0
for i in range(1, n + 1): # iterating over all possible pairs of horizontal lines
for j in range(1, m + 1): # iterating over all possible pairs of vertical lines
count += (n - i + 1) * (m - j + 1) # counting the number of rectangles that can be formed using these lines
return count
# driver code
def main():
n = 5
m = 4
print(rect_count(n, m))
if __name__ == "__main__":
main()
输出:150
时间复杂度: O(N^2)
空间复杂度: O(1)
我们已经讨论了如何计算 n*m 网格中的方块数,参考如下文章:
计算矩形中的正方形数量:
C++:https://blog.csdn.net/hefeng_aspnet/article/details/145686813
C语言:https://blog.csdn.net/hefeng_aspnet/article/details/145687009
Java:https://blog.csdn.net/hefeng_aspnet/article/details/145687069
Python:https://blog.csdn.net/hefeng_aspnet/article/details/145687138
C#:https://blog.csdn.net/hefeng_aspnet/article/details/145687205
javascript:https://blog.csdn.net/hefeng_aspnet/article/details/145687255
PHP:https://blog.csdn.net/hefeng_aspnet/article/details/145687312
现在让我们推导出矩形数量的公式:
如果网格是 1×1,则有 1 个矩形。
如果网格是 2×1,则会有 2 + 1 = 3 个矩形
如果网格是 3×1,则会有 3 + 2 + 1 = 6 个矩形。
我们可以说,对于 N*1,将有 N + (N-1) + (n-2) … + 1 = (N)(N+1)/2 个矩形
如果我们在 N×1 中再添加一列,那么首先,第二列中的矩形数量将与第一列一样多,
然后我们将有相同数量的 2×M 个矩形。
所以 N×2 = 3 (N)(N+1)/2
推导出来后我们可以说
对于 N*M 我们有 (M)(M+1)/2 (N)(N+1)/2 = M(M+1)(N)(N+1)/4
所以总矩形的公式将是 M(M+1)(N)(N+1)/4 。
组合逻辑:
N*M 网格可以表示为 (N+1) 条垂直线和 (M+1) 条水平线。
在矩形中,我们需要两条不同的水平线和两条不同的垂直线。
因此,按照组合数学的逻辑,我们可以选择 2 条垂直线和 2 条水平线来形成一个矩形。这些组合的总数就是网格中可能出现的矩形的数量。
N*M 网格中的矩形总数:N+1 C 2 * M+1 C 2 = (N*(N+1)/2!)*(M*(M+1)/2!) = N*(N+1)*M*(M+1)/4,公式如图:
示例代码:
# Python3 program to count number
# of rectangles in a n x m grid
def rectCount(n, m):
return (m * n * (n + 1) * (m + 1)) // 4
# Driver code
n, m = 5, 4
print(rectCount(n, m))
# This code is contributed by Anant Agarwal.
输出:150
时间复杂度: O(1)
辅助空间: O(1),因为没有占用额外的空间。
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。