Open In App

Number of rectangles in N*M grid

Last Updated : 30 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We are given a N*M grid, print the number of rectangles in it.
Examples: 

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

Recommended Practice

Brute Force Approach :

  • Iterate over all possible pairs of horizontal lines.
  • Iterate over all possible pairs of vertical lines.
  • count the number of rectangles that can be formed using these lines. 

Below is the code for the above approach :

C++




#include <bits/stdc++.h>
using namespace std;
 
int rectCount(int n, int m)
{
    int count = 0;
    for(int i=1; i<=n; i++) // iterating over all possible pairs of horizontal lines
    {
        for(int j=1; j<=m; j++) // 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 */
int main()
{
    int n = 5, m = 4;
    cout << rectCount(n, m);
    return 0;
}


Java




import java.util.Scanner;
 
public class RectangleCount {
    public static int rectCount(int n, int m) {
        int count = 0;
        // Iterate over all possible pairs of horizontal lines
        for (int i = 1; i <= n; i++) {
            // Iterate over all possible pairs of vertical lines
            for (int j = 1; j <= m; j++) {
                // Count the number of rectangles that can be formed using these lines
                count += (n - i + 1) * (m - j + 1);
            }
        }
        return count;
    }
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = 5, m = 4;
        // Calculate and print the count of rectangles
        System.out.println("Count of Rectangles: " + rectCount(n, m));
    }
}


Python3




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()


C#




using System;
 
class Program
{
    static int RectCount(int n, int m)
    {
        int count = 0;
        for (int i = 1; i <= n; i++) // iterating over all possible pairs of horizontal lines
        {
            for (int j = 1; j <= m; j++) // 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
    static void Main()
    {
        int n = 5, m = 4;
        Console.WriteLine(RectCount(n, m));
    }
}


Javascript




// Function to count the number of rectangles that can be formed
function rectCount(n, m) {
    let count = 0;
 
    for (let i = 1; i <= n; i++) { // iterating over all possible pairs of horizontal lines
        for (let j = 1; j <= m; j++) { // 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
const n = 5;
const m = 4;
console.log(rectCount(n, m));


Output

150







Time Complexity : O(N^2)
Space Complexity : O(1)

We have discussed counting number of squares in a n x m grid,
Let us derive a formula for number of rectangles.
If the grid is 1×1, there is 1 rectangle. 
If the grid is 2×1, there will be 2 + 1 = 3 rectangles 
If it grid is 3×1, there will be 3 + 2 + 1 = 6 rectangles. 
we can say that for N*1 there will be N + (N-1) + (n-2) … + 1 = (N)(N+1)/2 rectangles
If we add one more column to N×1, firstly we will have as many rectangles in the 2nd column as the first, 
and then we have that same number of 2×M rectangles. 
So N×2 = 3 (N)(N+1)/2
After deducing this we can say 
For N*M we’ll have (M)(M+1)/2 (N)(N+1)/2 = M(M+1)(N)(N+1)/4
So the formula for total rectangles will be M(M+1)(N)(N+1)/4 

.

Combinatorial Logic:

N*M grid can be represented as (N+1) vertical lines and (M+1) horizontal lines.
In a rectangle, we need two distinct horizontal and two distinct verticals.
So going by the logic of Combinatorial Mathematics we can choose 2 vertical lines and 2 horizontal lines to form a rectangle. And total number of these combinations is the number of rectangles possible in the grid.

Total Number of Rectangles in N*M grid: N+1C2 * M+1C2 = (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 <bits/stdc++.h>
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.


Javascript




<script>
 
    // Javascript Code to count number
    // of rectangles in N*M grid
     
    function rectCount(n, m)
    {
        return parseInt((m * n * (n + 1) *
                        (m + 1)) / 4, 10);
    }
     
      let n = 5, m = 4;
      document.write(rectCount(n, m));
     
</script>


PHP




<?php
// PHP program to count
// number of rectangles
// in a n x m grid
 
function rectCount($n, $m)
{
    return ($m * $n *
           ($n + 1) *
           ($m + 1)) / 4;
}
 
// Driver Code
$n = 5;
$m = 4;
echo rectCount($n, $m);
 
// This code is contributed
// by ajit
?>


Output

150







Time complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.

This article is contributed by Pranav.

 



Previous Article
Next Article

Similar Reads

Number of rectangles with given area in an N*M grid
Given three positive integers N, M, and A, the task is to count the number of rectangles with area equal to A present in an M * N grid. Examples: Input: N = 2, M = 2, A = 2 Output: 4 Explanation: In the given grid of size 2 × 2, 2 rectangles of dimension 2 × 1 and 2 rectangles of dimension 1 × 2 can be inscribed. Therefore, the required output is 4
10 min read
Print the indices for every row of a grid from which escaping from the grid is possible
Given a binary 2D array arr[] of dimension M * N representing a grid where '0' represents that there is a wall on the main diagonal of the cell and '1' represents that there is a wall on cross diagonal of the cell. The task is for every ith row is to print the index of the row from which one can escape the grid, given that one cannot escape from th
15 min read
Maximize median of a KxK sub-grid in an NxN grid
Given a square matrix arr[][] of size N consisting of non-negative integers and an integer K, the task is to find the maximum median value of the elements of a square submatrix of the size K. Examples: Input: arr[][] = {{1, 5, 12}, {6, 7, 11}, {8, 9, 10}}, N = 3, K = 2Output: 9Explanation: The median of all subsquare of size 2*2 are: The subsquare
14 min read
Find the number of rectangles of size 2*1 which can be placed inside a rectangle of size n*m
Given two integers n, m. Find the number of rectangles of size 2*1 that can be placed inside a rectangle of size n*m. Note: No two small rectangles overlap.Each small rectangle lies entirely inside the large rectangle. It is allowed to touch the edges of the large rectangle. Examples: Input : n = 3, m =3 Output : 4 Input : n = 2, m = 4 Output : 4 A
6 min read
Count the number of rectangles such that ratio of sides lies in the range [a,b]
Given the length and breadth of N rectangles and a range i.e. [a, b], the task is to count the number of rectangles whose sides(larger/smaller) ratio is in the range [a, b]. Examples: Input: {{165, 100}, {180, 100}, {100, 170}}, a = 1.6, b = 1.7 Output: 2 165/100 = 1.65 170/100 = 1.7 Input: {{10, 12}, {26, 19}}, a = 0.8, b = 1.2 Output: 1 Approach:
5 min read
Find the minimum number of rectangles left after inserting one into another
Given width and height of N rectangles. The task is to find the minimum number of rectangles left after inserting one into another. Note : If W1 &lt; W2 and H1 &lt; H2 then rectangle 1 fits inside rectangle 2.The smallest rectangle can insert in the second smallest, and this rectangle can insert in the next one and so forth. Examples: Input : arr[]
9 min read
Total number of unit cells covered by all given Rectangles
Given a matrix A[][] consisting of coordinates of N rectangles such that {A[i][0], A[i][1]} representing bottom left coordinate of rectangle and {A[i][2], A[i][3]} representing top right coordinate of rectangle, the task is to find the total number of cells covered by all rectangles. Examples: Input: N = 2, A[][] = {{1, 1, 3, 3}, {2, 1, 4, 2}} Outp
8 min read
Maximum number of overlapping rectangles with at least one common point
Given four arrays x1[], x2[], y1[], y2[] of size N where (x1[i], y1[i]) denotes the left-bottom corner and (x2[i], y2[i]) right-top corner of a rectangle, the task is to find the maximum number of overlapping rectangles with at least one common point. Examples: Input: N = 2 x1[] = {0, 50} y1[] = {0, 50} x2[] = {100, 60} y2[] = {100, 60}Output: 2Exp
8 min read
Find the number of corner rectangles that can be formed from given Matrix
Given a binary matrix mat[][] of dimensions N*M, the task is to find the number of corner rectangles that can be formed. A corner rectangle is defined as the submatrix having 1s on the corners of it and each 1s must belong to a unique cell in that submatrix. Examples: Input: mat[][] = {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}}Output: 1Explanation:There exis
7 min read
Number of rectangles in a circle of radius R
Given a circular sheet of radius R and the task is to find the total number of rectangles with integral length and width that can be cut from the circular sheet, one at a time. Examples: Input: R = 2 Output: 8 8 rectangles can be cut from a circular sheet of radius 2. These are: 1x1, 1x2, 2x1, 2x2, 1x3, 3x1, 2x3, 3x2.Input: R = 1 Output: 1 Only one
9 min read
Practice Tags :