The Wayback Machine - https://web.archive.org/web/20241125181552/https://www.geeksforgeeks.org/number-rectangles-nm-grid/
Open In App

Number of rectangles in N*M grid

Last Updated : 30 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 < W2 and H1 < 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
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
Number of unique rectangles formed using N unit squares
You are given N unit squares (squares with side length 1 unit), and you are asked to make rectangles using these squares. You have to count the number of rotationally unique rectangles than you can make. What does rotationally unique mean? Well, two rectangles are rotationally unique if one can't be rotated to become equivalent to the other one. Ex
4 min read
Find number of rectangles that can be formed from a given set of coordinates
Given an array arr[][] consisting of pair of integers denoting coordinates. The task is to count the total number of rectangles that can be formed using given coordinates. Examples: Input: arr[][] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}, {2, 0}, {2, 1}, {11, 11}}Output: 3Explanation: Following are the rectangles formed using given coordinates. First Rect
6 min read
Create a matrix with alternating rectangles of O and X
Write a code which inputs two numbers m and n and creates a matrix of size m x n (m rows and n columns) in which every elements is either X or 0. The Xs and 0s must be filled alternatively, the matrix should have outermost rectangle of Xs, then a rectangle of 0s, then a rectangle of Xs, and so on. Examples: Input: m = 3, n = 3 Output: Following mat
15 min read
Sum of Areas of Rectangles possible for an array
Given an array, the task is to compute the sum of all possible maximum area rectangles which can be formed from the array elements. Also, you can reduce the elements of the array by at most 1. Examples: Input: a = {10, 10, 10, 10, 11, 10, 11, 10} Output: 210 Explanation: We can form two rectangles one square (10 * 10) and one (11 * 10). Hence, tota
13 min read
Intersecting rectangle when bottom-left and top-right corners of two rectangles are given
Given coordinates of 4 points, bottom-left and top-right corners of two rectangles. The task is to find the coordinates of the intersecting rectangle formed by the given two rectangles. Examples: Input: rec1: bottom-left(0, 0), top-right(10, 8), rec2: bottom-left(2, 3), top-right(7, 9) Output: (2, 3) (7, 8) (2, 8) (7, 3) Input: rec1: bottom-left(0,
10 min read
Smallest square formed with given rectangles
Given a rectangle of length l and breadth b, we need to find the area of the smallest square which can be formed with the rectangles of these given dimensions. Examples: Input : 1 2 Output : 4 We can form a 2 x 2 square using two rectangles of size 1 x 2. Input : 7 10 Output :4900 Let's say we want to make a square of side length a from rectangles
6 min read
Check if it is possible to rearrange rectangles in a non-ascending order of breadths
Given n number of rectangles with it's L-length and B-Breadth. We can turn any rectangle by 90 degrees. In other words, after turning them, the breadth will become length and length will be breadth. The task is to check if there is a way to make the rectangles go in order of non-ascending breadth. That is, a breadth of every rectangle has to be not
7 min read
Maximum given sized rectangles that can be cut out of a sheet of paper
Given the length L and breadth B of a sheet of paper, the task is to find the maximum number of rectangles with given length l and breadth b that can be cut from this sheet of paper.Examples: Input: L = 5, B = 2, l = 14, b = 3 Output: 0 The sheet is smaller than the required rectangle. So, no rectangle of the given dimension can be cut from the she
6 min read
Largest subset of rectangles such that no rectangle fit in any other rectangle
Given height and width of N rectangles. The task is to find the size of the largest subset such that no pair of rectangles fit within each other. Note that if H1 ? H2 and W1 ? W2 then rectangle 1 fits inside rectangle 2. Examples: Input: arr[] = {{1, 3}, {2, 2}, {1, 3}} Output: 2 The required sub-set is {{1, 3}, {2, 2}} {1, 3} is included only once
15 min read
Count of distinct rectangles inscribed in an equilateral triangle
Given an equilateral triangle made of dots (.) joined together to form triangle and an integer n which represents the length of the sides of the triangle. The task is to count the number of rectangles that can be inscribed in the given triangle such that: Horizontal edges must be parallel to the base of the given triangle.Rectangle must only be for
11 min read
Count Distinct Rectangles in N*N Chessboard
Given a N x N Chessboard. The task is to count distinct rectangles from the chessboard. For example, if the input is 8 then the output should be 36.Examples: Input: N = 4 Output: 10 Input: N = 6 Output: 21 Approach: Suppose N = 8 i.e. 8 x 8 chessboard is given, So different rectangles that can be formed are: 1 x 1, 1 x 2, 1 x 3, 1 x 4, 1 x 5, 1 x 6
3 min read
Check if N rectangles of equal area can be formed from (4 * N) integers
Given an integer N and an array arr[] of size 4 * N, the task is to check whether N rectangles of equal area can be formed from this array if each element can be used only once. Examples: Input: arr[] = {1, 8, 2, 1, 2, 4, 4, 8}, N = 2 Output: Yes Two rectangles with sides (1, 8, 1, 8) and (2, 4, 2, 4) can be formed. Both of these rectangles have th
6 min read
Count of rectangles possible from N and M straight lines parallel to X and Y axis respectively
Given two integers N and M, where N straight lines are parallel to the X-axis and M straight lines are parallel to Y-axis, the task is to calculate the number of rectangles that can be formed by these lines. Examples: Input: N = 3, M = 6 Output: 45 Explanation: There are total 45 rectangles possible with 3 lines parallel to x axis and 6 lines paral
5 min read
Minimum area of square holding two identical rectangles
Given the length L and breadth B of two identical rectangles, the task is to find the minimum area of a square in which the two identical rectangles with dimensions L × B can be embedded.Examples: Input: L = 7, B = 4 Output: 64 Explanation: Two rectangles with sides 7 x 4 can fit into square with side 8. By placing two rectangles with side 4 upon e
4 min read
Find side of Square which makes minimal area to fit two identical rectangles inside it
Given height H, and width W, of a rectangle, the task is to find the side of a square of the minimum area in which two rectangles fit completely. Note: Two rectangles can touch each other by side or corner.Rectangles cannot intersect each other.Rectangles can also touch the sides of the square but must be completely inside it.The Rectangles can be
12 min read
Missing vertex among N axis-parallel rectangles
Given N axis-parallel rectangles in a 2-D Cartesian coordinate system and coordinates of 4N-1 vertices, the task is to find the single vertex missing. Examples: Input: N = 2, V[][] = {{1, 1}, {1, 2}, {4, 6}, {2, 1}, {9, 6}, {9, 3}, {4, 3}}Output: {2, 2} Explanation: The coordinates forming an axis parallel rectangle are {4, 6}, {9, 6}, {4, 3}, {9,
9 min read
Count of Rectangles with area K made up of only 1s from given Binary Arrays
Given two binary arrays A[] and B[], of length N and M respectively, the task is to find the number of rectangles of area K consisting of 1's in the matrix C[][] generated by multiplying the two arrays such that, C[i][j] = A[i] * B[j] (1< i < n, 1< j < m). Examples: Input: N= 3, M = 3, A[] = {1, 1, 0}, B[] = {0, 1, 1}, K = 2 Output: 4 E
11 min read
Count of smaller rectangles that can be placed inside a bigger rectangle
Given four integers L, B, l, and b, where L and B denote the dimensions of a bigger rectangle and l and b denotes the dimension of a smaller rectangle, the task is to count the number of smaller rectangles that can be drawn inside a bigger rectangle. Note: Smaller rectangles can overlap partially. Examples: Input: L = 5, B = 3, l = 4, b = 1Output:
5 min read
Perimeter of the Union of Two Rectangles
Given two arrays X[] and Y[], each of length 4, where (X[0], Y[0]) and (X[1], Y[1]) represents the bottom left and top right corners of one rectangle and (X[2], Y[2]) and (X[3], Y[3]) represents the bottom left and top right corners of the other rectangle, the task is to find the perimeter of the outer boundaries of the union of the two rectangles
7 min read
Count rectangles generated in a given rectangle by lines drawn parallel to X and Y axis from a given set of points
Given a 2D array rectangle[][] representing vertices of a rectangle {(0, 0), (L, 0), (0, B), (L, B)} of dimensions L * B, and another 2D-array, points[][] of size N in a Cartesian coordinate system. Draw a horizontal line parallel to the X-axis and a vertical line parallel to the Y-axis from each point of the given array. The task is to count all p
6 min read
Size of smallest square that contains N non-overlapping rectangles of given dimensions
Given two positive integers W and H and N rectangles of dimension W*H, the task is to find the smallest size of the square required such that all the N rectangles can be packed without overlapping. Examples: Input: N = 10, W = 2, H = 3Output: 9Explanation:The smallest size of the square is 9 units to pack the given 10 rectangles of size 2*3 as illu
7 min read
Practice Tags :
three90RightbarBannerImg