📜  N * M网格中的矩形数

📅  最后修改于: 2021-05-08 16:19:09             🧑  作者: Mango

给我们一个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


我们已经讨论了在axm网格中计算平方数,
让我们导出矩形数量的公式。
如果网格为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


输出:

150