给定一个 N*M 的网格,打印其中的矩形数量。
例子:
Input : N = 2, M = 2
Output : 9
There are 4 rectangles of size 1 x 1.
There are 2 rectangles of size 1 x 2
There are 2 rectangles of size 2 x 1
There is one rectangle of size 2 x 2.
Input : N = 5, M = 4
Output : 150
Input : N = 4, M = 3
Output: 60
我们已经讨论过计算 anxm 网格中的方块数,
让我们推导出矩形数量的公式。
如果网格为 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
C++
// C++ program to count number of rectangles
// in a n x m grid
#include
using namespace std;
int rectCount(int n, int m)
{
return (m * n * (n + 1) * (m + 1)) / 4;
}
/* driver code */
int main()
{
int n = 5, m = 4;
cout << rectCount(n, m);
return 0;
}
Java
// JAVA Code to count number of
// rectangles in N*M grid
import java.util.*;
class GFG {
public static long rectCount(int n, int m)
{
return (m * n * (n + 1) * (m + 1)) / 4;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int n = 5, m = 4;
System.out.println(rectCount(n, m));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
# 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.
C#
// C# Code to count number of
// rectangles in N*M grid
using System;
class GFG {
public static long rectCount(int n, int m)
{
return (m * n * (n + 1) * (m + 1)) / 4;
}
// Driver program
public static void Main()
{
int n = 5, m = 4;
Console.WriteLine(rectCount(n, m));
}
}
// This code is contributed by Anant Agarwal.
PHP
Javascript
输出:
150