The Wayback Machine - https://web.archive.org/web/20241008190602/https://www.geeksforgeeks.org/number-of-square-matrices-with-all-1s/
Open In App

Number of square matrices with all 1s

Last Updated : 14 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an N*M matrix containing only 0s and 1s, the task is to count the number of square submatrices containing all 1s.

Examples: 

Input: arr[][] = {{0, 1, 1, 1}, 
{1, 1, 1, 1}, 
{0, 1, 1, 1}} 
Output: 15 
Explanation: 
There are 10 squares of side length 1. 
There are 4 squares of side length 2. 
There is 1 square of side length 3. 
Total number of squares = 10 + 4 + 1 = 15.

Input: arr[][] = {{1, 1}, 
{1, 1}, 
{1, 1}} 
Output: 8
There are 6 squares of length 1
There are 2 squares of length 2

Input: arr[][] = {{1, 0, 1}, 
{1, 1, 0}, 
{1, 1, 0}} 
Output: 7 

Naive Recursion Approach:

  • At every position, we determine the maximum possible side length for a square if we consider that position as the top left corner.
  • Therefore, we can calculate the total number of squares as sum of these lengths

How do we compute total numbers of squares that have arr[i][j] as the top left.

  1. If arr[i][j] is 0, we return 0 and do not proceed.
  2. We initialize res = 0
  3. If arr[i][j] is 1, then we add 1 to the result.
  4. Now we recursively compute number of squares where right or arr[i][j+1], below or arr[i+1][j] and below-right or arr[i+1][j+1] are individually top left corners. And take take the minimum of these 3 and add to the result.
C++
#include <bits/stdc++.h>
using namespace std;

// Function to solve the problem recursively
int sqRec(vector<vector<int>>& arr, int i, int j)
{
    // Base case: if out of bounds or current element is 0
    if (i < 0 or i >=  arr.size() or 
        j < 0 or j >= arr[0].size() or arr[i][j] == 0) 
        return 0;

    // Return the count of squares for the current position
    return 1 + min({ sqRec(arr, i, j + 1),  // Right
                     sqRec(arr, i + 1, j),  // Below
                     sqRec(arr, i + 1, j + 1) }); // Below-Right
}

// Function to return the number of square submatrices with all 1s
int countSquarrs(vector<vector<int>>& arr)
{
    int res = 0;
  
    // Iterate over each element of the matrix
    for (int i = 0; i < arr.size(); i++) {
        for (int j = 0; j < arr[0].size(); j++) {
            if (arr[i][j] == 1) {
              
                // If current element is 1, recursively
                // calculate the number of squares and
                // add it to the answer
                res += sqRec(arr, i, j);
            }
        }
    }
  
    return res;
}

// Driver code
int main()
{
    vector<vector<int>> arr = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } };

    cout << countSquarrs(arr);

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class SquareSubmatrices {
    // Function to solve the problem recursively
    static int solve(List<List<Integer>> matrix, int m, int n, int i, int j) {
        // Base case: if out of bounds or current element is 0
        if (i < 0 || i >= m || j < 0 || j >= n || matrix.get(i).get(j) == 0) {
            return 0;
        }

        // Recursive calls to calculate the number of squares in right, bottom, and bottom-right directions
        int right = solve(matrix, m, n, i, j + 1);
        int bottom = solve(matrix, m, n, i + 1, j);
        int bottomRight = solve(matrix, m, n, i + 1, j + 1);

        // Return the count of squares for the current position
        return 1 + Math.min(Math.min(right, bottom), bottomRight);
    }

    // Function to return the number of square submatrices with all 1s
    static int countSquareMatrices(List<List<Integer>> matrix) {
        int m = matrix.size();
        int n = matrix.get(0).size();
        int ans = 0;

        // Iterate over each element of the matrix
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix.get(i).get(j) == 1) {
                    // If current element is 1, recursively calculate the number of squares and add it to the answer
                    ans += solve(matrix, m, n, i, j);
                }
            }
        }

        // Return the final answer
        return ans;
    }

    // Driver code
    public static void main(String[] args) {
        List<List<Integer>> arr = new ArrayList<>();
        arr.add(List.of(1, 0, 1));
        arr.add(List.of(1, 1, 0));
        arr.add(List.of(1, 1, 0));

        System.out.println(countSquareMatrices(arr));
    }
}
Python
def solve(matrix, m, n, i, j):
    # Base case: if out of bounds or current element is 0
    if i < 0 or i >= m or j < 0 or j >= n or matrix[i][j] == 0:
        return 0

    # Recursive calls to calculate the number of squares in right, bottom, and bottom-right directions
    right = solve(matrix, m, n, i, j + 1)
    bottom = solve(matrix, m, n, i + 1, j)
    bottom_right = solve(matrix, m, n, i + 1, j + 1)

    # Return the count of squares for the current position
    return 1 + min(right, bottom, bottom_right)


def countSquareMatrices(matrix):
    m = len(matrix)
    n = len(matrix[0])
    ans = 0

    # Iterate over each element of the matrix
    for i in range(m):
        for j in range(n):
            if matrix[i][j] == 1:
                # If current element is 1, recursively calculate the number of squares and add it to the answer
                ans += solve(matrix, m, n, i, j)

    # Return the final answer
    return ans


# Driver code
arr = [[1, 0, 1], [1, 1, 0], [1, 1, 0]]
print(countSquareMatrices(arr))
C#
using System;
using System.Collections.Generic;

public class GFG
{
    // Function to solve the problem recursively
    public static int Solve(List<List<int>> matrix, int m, int n, int i, int j)
    {
        // Base case: if out of bounds or current element is 0
        if (i < 0 || i >= m || j < 0 || j >= n || matrix[i][j] == 0)
        {
            return 0;
        }

        // Recursive calls to calculate the number of squares in
        // right, bottom, and bottom-right directions
        int right = Solve(matrix, m, n, i, j + 1);
        int bottom = Solve(matrix, m, n, i + 1, j);
        int bottom_right = Solve(matrix, m, n, i + 1, j + 1);

        // Return the count of squares for the current position
        return 1 + Math.Min(Math.Min(right, bottom), bottom_right);
    }

    // Function to return the number of square submatrices with all 1s
    public static int CountSquareMatrices(List<List<int>> matrix)
    {
        int m = matrix.Count;
        int n = matrix[0].Count;
        int ans = 0;

        // Iterate over each element of the matrix
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (matrix[i][j] == 1)
                {
                    // If current element is 1, recursively calculate
                    // the number of squares and add it to the answer
                    ans += Solve(matrix, m, n, i, j);
                }
            }
        }

        // Return the final answer
        return ans;
    }

    // Driver code
    public static void Main(string[] args)
    {
        List<List<int>> arr = new List<List<int>>()
        {
            new List<int>() { 1, 0, 1 },
            new List<int>() { 1, 1, 0 },
            new List<int>() { 1, 1, 0 }
        };

        Console.WriteLine(CountSquareMatrices(arr));
    }
}
JavaScript
<script>
// JavaScript program to return the number of
// square submatrices with all 1s

// Function to solve the problem recursively
function solve(matrix, m, n, i, j) {
    // Base case: if out of bounds or current element is 0
    if (i < 0 || i >= m || j < 0 || j >= n || matrix[i][j] === 0) {
        return 0;
    }

    // Recursive calls to calculate the number of squares in
    // right, bottom, and bottom-right directions
    const right = solve(matrix, m, n, i, j + 1);
    const bottom = solve(matrix, m, n, i + 1, j);
    const bottom_right = solve(matrix, m, n, i + 1, j + 1);

    // Return the count of squares for the current position
    return 1 + Math.min(right, bottom, bottom_right);
}

// Function to return the number of square submatrices with
// all 1s
function countSquareMatrices(matrix) {
    const m = matrix.length;
    const n = matrix[0].length;
    let ans = 0;

    // Iterate over each element of the matrix
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (matrix[i][j] === 1) {
                // If current element is 1, recursively
                // calculate the number of squares and add
                // it to the answer
                ans += solve(matrix, m, n, i, j);
            }
        }
    }

    // Return the final answer
    return ans;
}

// Driver code
const arr = [
    [1, 0, 1],
    [1, 1, 0],
    [1, 1, 0]
];

document.write(countSquareMatrices(arr));

// This code is contributed by Susobhan Akhuli
</script>

Output
7

Time Complexity: Exponential

Using Memoization:

There are overlapping subproblems as we make three calls for adjacent cells of every cell. So we can optimize the recursive solution. We make a 2D memo array to store the results of already computed subptoblems. We make it 2D because there are two parameters (i and j) that change in recursion. We make the size of memo as m x n because these parameters range from 0 to m-1 and 0 to n-1 respectively. We initialize the memo array as -1 to indiciate nothing is computed and before making a recursive call, we check if the value for the current position is already present in the memo.. If so, it directly returns that value instead of recomputing it.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to solve the problem recursively with memoization
int sqRec(vector<vector<int>>& arr, int i, int j, vector<vector<int>>& memo)
{

    // Base case: if out of bounds or current element is 0
    if (i < 0 or i >= arr.size() or 
        j < 0 or j >= arr[j].size() or arr[i][j] == 0)       
        return 0;

    // If the result is already computed, return it
    if (memo[i][j] != -1)
        return memo[i][j];

    // Calculate the count of squares for the current position
    // and store it in the memo array
    memo[i][j] = 1 + min({ sqRec(arr, i, j + 1, memo),  // Right
                           sqRec(arr, i + 1, j, memo),  // Below
                           sqRec(arr, i + 1, j + 1, memo) }); // Below-Right

    return memo[i][j];
}

// Function to return the number of square submatrices with all 1s
int countSquarrs(vector<vector<int>>& arr)
{
    int m = arr.size();
    int n = arr[0].size();
    int res = 0;

    // Initialize memoization matrix with -1
    vector<vector<int>> memo(m, vector<int>(n, -1));

    // Iterate over each element of the matrix
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (arr[i][j] == 1) {
              
                // If current element is 1, recursively calculate
                // the number of squares and add it to the result
                res += sqRec(arr, i, j, memo);
            }
        }
    }

    return res;
}

// Driver code
int main()
{
    vector<vector<int>> arr = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } };
    cout << countSquarrs(arr);
    return 0;
}
Java
import java.util.*;

public class SquareSubmatrices {
    // Recursive function to solve the problem
    static int solve(int[][] matrix, int m, int n, int i,
                     int j, int[][] dp)
    {
        // Base case: if out of bounds or current element is
        // 0
        if (i < 0 || i >= m || j < 0 || j >= n
            || matrix[i][j] == 0) {
            return 0;
        }

        // If the value is already calculated, return it
        // from dp table
        if (dp[i][j] != -1)
            return dp[i][j];

        // Recursive calls to calculate the number of
        // squares in right, bottom, and bottom-right
        // directions
        int right = solve(matrix, m, n, i, j + 1, dp);
        int bottom = solve(matrix, m, n, i + 1, j, dp);
        int bottomRight
            = solve(matrix, m, n, i + 1, j + 1, dp);

        // Memoize the calculated value and return it
        return dp[i][j]
            = 1
              + Math.min(Math.min(right, bottom),
                         bottomRight);
    }

    // Function to return the number of square submatrices
    // with all 1s
    static int countSquareMatrices(int[][] matrix)
    {
        int m = matrix.length;
        int n = matrix[0].length;

        // Create a dp table to store the results of
        // subproblems
        int[][] dp = new int[m + 1][n + 1];
        for (int[] row : dp) {
            Arrays.fill(row, -1);
        }

        int ans = 0;

        // Iterate over each element of the matrix
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 1) {
                    // If the current element is 1,
                    // recursively calculate the number of
                    // squares and add it to the answer
                    ans += solve(matrix, m, n, i, j, dp);
                }
            }
        }

        // Return the final answer
        return ans;
    }

    // Driver code
    public static void main(String[] args)
    {
        int[][] arr
            = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } };

        System.out.println(countSquareMatrices(arr));
    }
}
Python
# Recursive function to solve the problem
def solve(matrix, m, n, i, j, dp):
    # Base case: if out of bounds or current element is 0
    if i < 0 or i >= m or j < 0 or j >= n or matrix[i][j] == 0:
        return 0

    # If the value is already calculated, return it from dp table
    if dp[i][j] != -1:
        return dp[i][j]

    # Recursive calls to calculate the number of squares in right, bottom, and bottom-right directions
    right = solve(matrix, m, n, i, j + 1, dp)
    bottom = solve(matrix, m, n, i + 1, j, dp)
    bottom_right = solve(matrix, m, n, i + 1, j + 1, dp)

    # Memoize the calculated value and return it
    dp[i][j] = 1 + min(right, bottom, bottom_right)
    return dp[i][j]

# Function to return the number of square submatrices with all 1s


def countSquareMatrices(matrix):
    m = len(matrix)
    n = len(matrix[0])

    # Create a dp table to store the results of subproblems
    dp = [[-1] * (n + 1) for _ in range(m + 1)]

    ans = 0

    # Iterate over each element of the matrix
    for i in range(m):
        for j in range(n):
            if matrix[i][j] == 1:
                # If the current element is 1, recursively calculate the number of squares and add it to the answer
                ans += solve(matrix, m, n, i, j, dp)

    # Return the final answer
    return ans


# Driver code
arr = [[1, 0, 1], [1, 1, 0], [1, 1, 0]]
print(countSquareMatrices(arr))
C#
using System;

public class GFG
{
    // Recursive function to solve the problem
    public static int Solve(int[][] matrix, int m, int n, int i, int j, int[][] dp)
    {
        // Base case: if out of bounds or current element is 0
        if (i < 0 || i >= m || j < 0 || j >= n || matrix[i][j] == 0)
        {
            return 0;
        }

        // If the value is already calculated, return it from dp table
        if (dp[i][j] != -1)
            return dp[i][j];

        // Recursive calls to calculate the number of squares in right, 
       // bottom, and bottom-right directions
        int right = Solve(matrix, m, n, i, j + 1, dp);
        int bottom = Solve(matrix, m, n, i + 1, j, dp);
        int bottomRight = Solve(matrix, m, n, i + 1, j + 1, dp);

        // Memoize the calculated value and return it
        return dp[i][j] = 1 + Math.Min(right, Math.Min(bottom, bottomRight));
    }

    // Function to return the number of square submatrices with all 1s
    public static int CountSquareMatrices(int[][] matrix)
    {
        int m = matrix.Length;
        int n = matrix[0].Length;

        // Create a dp table to store the results of subproblems
        int[][] dp = new int[m + 1][];
        for (int i = 0; i <= m; i++)
        {
            dp[i] = new int[n + 1];
            for (int j = 0; j <= n; j++)
            {
                dp[i][j] = -1;
            }
        }

        int ans = 0;

        // Iterate over each element of the matrix
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (matrix[i][j] == 1)
                {
                    // If the current element is 1, recursively 
                   // calculate the number of squares and add it to the answer
                    ans += Solve(matrix, m, n, i, j, dp);
                }
            }
        }

        // Return the final answer
        return ans;
    }

    // Driver code
    public static void Main(string[] args)
    {
        int[][] arr = new int[][] {
            new int[] { 1, 0, 1 },
            new int[] { 1, 1, 0 },
            new int[] { 1, 1, 0 }
        };

        Console.WriteLine(CountSquareMatrices(arr));
    }
}
JavaScript
// Recursive function to solve the problem
function solve(matrix, m, n, i, j, dp) {
    // Base case: if out of bounds or current element is 0
    if (i < 0 || i >= m || j < 0 || j >= n || matrix[i][j] === 0) {
        return 0;
    }

    // If the value is already calculated, return it from dp table
    if (dp[i][j] !== -1) {
        return dp[i][j];
    }

    // Recursive calls to calculate the number of squares in
    // right, bottom, and bottom-right directions
    const right = solve(matrix, m, n, i, j + 1, dp);
    const bottom = solve(matrix, m, n, i + 1, j, dp);
    const bottomRight = solve(matrix, m, n, i + 1, j + 1, dp);

    // Memoize the calculated value and return it
    return (dp[i][j] = 1 + Math.min(right, bottom, bottomRight));
}

// Function to return the number of square submatrices with all 1s
function countSquareMatrices(matrix) {
    const m = matrix.length;
    const n = matrix[0].length;

    // Create a dp table to store the results of subproblems
    const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(-1));

    let ans = 0;

    // Iterate over each element of the matrix
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (matrix[i][j] === 1) {
                // If the current element is 1, recursively
                // calculate the number of squares and add
                // it to the answer
                ans += solve(matrix, m, n, i, j, dp);
            }
        }
    }

    // Return the final answer
    return ans;
}

// Example usage
const matrix = [
    [1, 0, 1],
    [1, 1, 0],
    [1, 1, 0],
];

console.log(countSquareMatrices(matrix));

Output
7

Time Complexity: O(m x n)
Auxiliary Space: O(1)

Using DP Buttom-Up:

This problem can be solved using Dynamic Programming.  

  1. Let the array dp[i][j] store the number of square matrices ending at (i, j)
  2. The recurrence relation to find the number of squares ending at (i, j) can be given by:
    • If dp[i][j] is 1:
      • dp[i][j] = min( min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1
    • Else if arr[i][j] is 0: 
      • dp[i][j] = 0
  3. Calculate the sum of the array which is equal to the number of square submatrices with all 1s.

Below is the implementation of the above approach:  

CPP
#include <bits/stdc++.h>
using namespace std;

// Function to return the number of square submatrices with all 1s
int countSquares(vector<vector<int>>& arr)
{
    int m = arr.size();
    int n = arr[0].size();

    // Create a dp array of the same size as the matrix
    vector<vector<int>> dp(m, vector<int>(n, 0));

    // Fill the first row (i = 0)
    for (int j = 0; j < n; j++) 
        dp[0][j] = arr[0][j];

    // Fill the first column (j = 0)
    for (int i = 1; i < m; i++) 
        dp[i][0] = arr[i][0];

    // Fill the rest of the dp array
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            if (arr[i][j] == 1) {
                dp[i][j] = 1 + min({ dp[i - 1][j],     // Top
                                     dp[i][j - 1],     // Left
                                     dp[i - 1][j - 1]  // Top-left diagonal
                                   });
            }
        }
    }
    
    // Result is sum of all dp values
    int res = 0;
    for (int i=0; i<n; i++) 
       for (int j=0; j<m; j++)
           res += dp[i][j];

    return res;
}

// Driver code
int main()
{
    vector<vector<int>> arr = { { 1, 0, 1 }, 
                               { 1, 1, 0 }, 
                               { 1, 1, 0 } };
    cout << countSquares(arr);

    return 0;
}
Java
// Java program to return the number of 
// square submatrices with all 1s
class GFG 
{
    
    final static int n = 3; 
    final static int m = 3; 
    
    // Function to return the number of 
    // square submatrices with all 1s 
    static int countSquareMatrices(int a[][], int N, int M) 
    { 
        // Initialize count variable 
        int count = 0; 
    
        for (int i = 1; i < N; i++)
        { 
            for (int j = 1; j < M; j++) 
            { 
                // If a[i][j] is equal to 0 
                if (a[i][j] == 0) 
                    continue; 
    
                // Calculate number of 
                // square submatrices 
                // ending at (i, j) 
                a[i][j] = Math.min(Math.min(a[i - 1][j], a[i][j - 1]), 
                            a[i - 1][j - 1]) + 1; 
            } 
        } 
    
        // Calculate the sum of the array 
        for (int i = 0; i < N; i++) 
            for (int j = 0; j < M; j++) 
                count += a[i][j]; 
    
        return count; 
    } 
    
    // Driver code 
    public static void main (String[] args)
    { 
        int arr[][] = { { 1, 0, 1 }, 
                        { 1, 1, 0 }, 
                        { 1, 1, 0 } }; 
    
        System.out.println(countSquareMatrices(arr, n, m)); 
    } 
}

// This code is contributed by AnkitRai01
Python
# Python3 program to return the number of
# square submatrices with all 1s
n = 3
m = 3

# Function to return the number of
# square submatrices with all 1s
def countSquareMatrices(a, N, M):
    
    # Initialize count variable
    count = 0

    for i in range(1, N):
        for j in range(1, M):
            
            # If a[i][j] is equal to 0
            if (a[i][j] == 0):
                continue

            # Calculate number of
            # square submatrices
            # ending at (i, j)
            a[i][j] = min([a[i - 1][j], 
                      a[i][j - 1], a[i - 1][j - 1]])+1

    # Calculate the sum of the array
    for i in range(N):
        for j in range(M):
            count += a[i][j]

    return count

# Driver code

arr = [ [ 1, 0, 1],
    [ 1, 1, 0 ],
    [ 1, 1, 0 ] ]

print(countSquareMatrices(arr, n, m))

# This code is contributed by mohit kumar 29
C#
// C# program to return the number of 
// square submatrices with all 1s
using System;

class GFG 
{
    
    static int n = 3; 
    static int m = 3; 
    
    // Function to return the number of 
    // square submatrices with all 1s 
    static int countSquareMatrices(int [,]a, int N, int M) 
    { 
        // Initialize count variable 
        int count = 0; 
    
        for (int i = 1; i < N; i++)
        { 
            for (int j = 1; j < M; j++) 
            { 
                // If a[i][j] is equal to 0 
                if (a[i, j] == 0) 
                    continue; 
    
                // Calculate number of 
                // square submatrices 
                // ending at (i, j) 
                a[i, j] = Math.Min(Math.Min(a[i - 1, j], a[i, j - 1]), 
                            a[i - 1, j - 1]) + 1; 
            } 
        } 
    
        // Calculate the sum of the array 
        for (int i = 0; i < N; i++) 
            for (int j = 0; j < M; j++) 
                count += a[i, j]; 
    
        return count; 
    } 
    
    // Driver code 
    public static void Main()
    { 
        int [,]arr = { { 1, 0, 1 }, 
                        { 1, 1, 0 }, 
                        { 1, 1, 0 } }; 
    
        Console.WriteLine(countSquareMatrices(arr, n, m)); 
    } 
}

// This code is contributed by AnkitRai01
JavaScript
<script>

// Javascript program to return the number of
// square submatrices with all 1s

var n = 3
var m = 3

// Function to return the number of
// square submatrices with all 1s
function countSquareMatrices(a, N, M)
{
    // Initialize count variable
    var count = 0;

    for (var i = 1; i < N; i++) {
        for (var j = 1; j < M; j++) {
            // If a[i][j] is equal to 0
            if (a[i][j] == 0)
                continue;

            // Calculate number of
            // square submatrices
            // ending at (i, j)
            a[i][j] = Math.min(Math.min(a[i - 1][j],
                              a[i][j - 1]),
                          a[i - 1][j - 1])
                      + 1;
        }
    }

    // Calculate the sum of the array
    for (var i = 0; i < N; i++)
        for (var j = 0; j < M; j++)
            count += a[i][j];

    return count;
}

// Driver code
var arr = [ [ 1, 0, 1 ],
                 [ 1, 1, 0 ],
                 [ 1, 1, 0 ] ];
document.write( countSquareMatrices(arr, n, m));

</script>

Output
7

Time Complexity: O(m x n)
Auxiliary Space: O(1)



Similar Reads

Count number of square sub matrices of given matrix whose sum of all cells is equal to S | Set 2
Given a matrix, arr[][] of dimensions M*N, and an integer S, the task is to print the count of the number of subsquares of the matrix, whose sum is equal to S. Examples: Input: M = 4, N = 5, S = 10, arr[][]={{2, 4, 3, 2, 10}, {3, 1, 1, 1, 5}, {1, 1, 2, 1, 4}, {2, 1, 1, 1, 3}} Output: 3 Explanation: Sub-squares {10}, {{2, 4}, {3, 1}} and {{1, 1, 1},
12 min read
Check if matrix can be converted to another matrix by transposing square sub-matrices
Given two N X M matrices of integers. In an operation, we can transpose any square sub-matrix in matrix1. The task is to check if matrix1 can be converted to matrix2 with the given operation.Examples: Input: matrix1[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, matrix2[][] = { {1, 4, 7}, {2, 5, 6}, {3, 8, 9}} Output: Yes Transpose the whole matrix and
10 min read
A square matrix as sum of symmetric and skew-symmetric matrices
Let A be a square matrix with all real number entries. Find two symmetric matrix P and skew symmetric matrix Q such that P + Q = A. Symmetric Matrix:- A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the original matrix. Skew Symmetric Matrix:- A square matrix is said to be skew symmetric matrix if the negati
9 min read
Check if a number is a perfect square having all its digits as a perfect square
Given an integer N, the task is to check if the given number is a perfect square having all its digits as a perfect square or not. If found to be true, then print “Yes”. Otherwise, print “No”.Examples: Input: N = 144 Output: Yes Explanation: The number 144 is a perfect square and also the digits of the number {1(= 12, 4(= 22} is also a perfect squa
11 min read
Find smallest perfect square number A such that N + A is also a perfect square number
Given a positive number N. The task is to find out the smallest perfect square number A such that N + A is also a perfect square number or return -1.Examples: Input: N = 3 Output: 1 Explanation: As 1 + 3 = 4 = 22 Input: N=1 Output: -1 Naive Approach: Traverse M from {1, 2, 3, 4, 5...} and check whether (N + M * M) is a perfect square number or not.
9 min read
Smallest N digit number whose sum of square of digits is a Perfect Square
Given an integer N, find the smallest N digit number such that the sum of the square of digits (in decimal representation) of the number is also a perfect square. If no such number exists, print -1.Examples: Input : N = 2 Output : 34 Explanation: The smallest possible 2 digit number whose sum of square of digits is a perfect square is 34 because 32
15+ min read
Check if a number is perfect square without finding square root
Check whether a number is a perfect square or not without finding its square root. Examples: Input: n = 36 Output: Yes Input: n = 12 Output: No Recommended PracticeCheck perfect squareTry It! Method 1:The idea is to run a loop from i = 1 to floor(sqrt(n)) and then check if squaring it makes n. Below is the implementation: C/C++ Code // C++ program
9 min read
XOR of XORs of all sub-matrices
Given a 'N*N' matrix, the task is to find the XOR of XORs of all possible sub-matrices.Examples: Input :arr = {{3, 1}, {1, 3}} Output : 0 Explanation: All the elements lie in 4 submatrices each. 4 being even, there total contribution towards final answer becomes 0. Thus, ans = 0. Input : arr = {{6, 7, 13}, {8, 3, 4}, {9, 7, 6}}; Output : 4 A Simple
6 min read
Queries on number of Binary sub-matrices of Given size
Given a Binary Matrix of size N X M, the task is to answer Q queries of the following type; Query(a, b): Find the number of sub matrices of size a X a with each of its element consisting of the Binary Number b. We basically need to find submatrices of given sizes with all 1s or all 0s. Examples: Input : N = 5, M = 4 m[][] = { { 0, 0, 1, 1 }, { 0, 0
12 min read
Count of matrices (of different orders) with given number of elements
Given a number N denotes the total number of elements in a matrix, the task is to print all possible order of matrix. An order is a pair (m, n) of integers where m is number of rows and n is number of columns. For example, if the number of elements is 8 then all possible orders are: (1, 8), (2, 4), (4, 2), (8, 1).Examples: Input: N = 8 Output: (1,
5 min read
Solid square inside a hollow square | Pattern
Given the value of n, print a hollow square of side length n and inside it a solid square of side length (n - 4) using stars(*). Examples : Input : n = 6 Output : ****** * * * ** * * ** * * * ****** Input : n = 11 Output : *********** * * * ******* * * ******* * * ******* * * ******* * * ******* * * ******* * * ******* * * * *********** C/C++ Code
5 min read
Count of pair of integers (x , y) such that difference between square of x and y is a perfect square
Given an integer N. The task is to find the number of pairs of integers (x, y) both less than N and greater than 1, such that x2 - y is a square number or 0. Example: Input: N = 3Output: 2Explanation:The only possible valid pairs are (1, 1), (2, 3). Therefore, the count of such pairs is 2. Input: N = 2Output: 1 Naive Approach: The simplest approach
11 min read
Area of a triangle with two vertices at midpoints of opposite sides of a square and the other vertex lying on vertex of a square
Given a positive integer N representing the side of a square, the task is to find the area of a triangle formed by connecting the midpoints of two adjacent sides and vertex opposite to the two sides. Examples: Input: N = 10Output: 37.5 Input: N = 1Output: 0.375 Approach: The given problem can be solved based on the following observations: The one s
5 min read
Count of numbers in range [L, R] having sum of digits of its square equal to square of sum of digits
Given two integers L and R, the task is to find the count of numbers in range [L, R] such that the sum of digits of its square is equal to the square of sum of its digits, Example: Input: L = 22, R = 22Output: 1Explanation: 22 is only valid number in this range as sum of digits of its square = S(22*22) = S(484) = 16 and square of sum of its digits
11 min read
Count integers whose square lie in given range and digits are perfect square
Given two integers L and R. Then the task is to output the count of integers X, such that L â‰Ī X2 â‰Ī R and X2 only consist of digits, which are perfect squares. Examples: Input: L = 167, R = 456Output: 2Explanation: Two numbers are 20 and 21, Their squares are 400 and 441 respectively. It can be verified that squares of both 20 and 21 are in the rang
13 min read
Count square and non-square numbers before n
Given a number n, we need to count square numbers smaller than or equal to n.Examples : Input : n = 5Output : Square Number : 2 Non-square numbers : 3Explanation : Square numbers are 1 and 4.Non square numbers are 2, 3 and 5.Input : n = 10Output : Square Number : 3 Non-square numbers : 7Explanation : Square numbers are 1, 4 and 9.Non square numbers
5 min read
Program for subtraction of matrices
The below program subtracts of two square matrices of size 4*4, we can change N for a different dimension. Implementation: C/C++ Code // C++ program for subtraction of matrices #include <bits/stdc++.h> using namespace std; #define N 4 // This function subtracts B[][] from A[][], and stores // the result in C[][] void subtract(int A[][N], int
7 min read
Operations on Sparse Matrices
Given two sparse matrices (Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists)), perform operations such as add, multiply or transpose of the matrices in their sparse form itself. The result should consist of three sparse matrices, one obtained by adding the two input matrices, one by multiplying the two matrices and one o
15+ min read
Python List Equality | Program to check if two given matrices are identical
We are given two square matrices of same order. Check if two given matrices are identical. Examples: Input : A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] Output: Matrices are identical We have existing solution for this problem please refer C Program to check if two give
3 min read
Find the intersection of two Matrices
Given two matrix A[][] and B[][] of same order m*n. The task is to find the intersection of both matrix as C, where: Cij = Aij if Aij = BijC = "*", otherwise. Examples: Input : A[N][N] = {{2, 4, 6, 8}, {1, 3, 5, 7}, {8, 6, 4, 2}, {7, 5, 3, 1}}; B[N][N] = {{0, 4, 3, 8}, {1, 3, 5, 7}, {8, 3, 6, 2}, {4, 5, 3, 4}}; Output : * 4 * 8 1 3 5 7 8 * * 2 * 5
6 min read
Check if it is possible to make two matrices strictly increasing by swapping corresponding values only
Given two n * m matrices A[][] and B[][], the task is to make both the matrices strictly increasing (both rows and columns) only by swapping two elements in different matrices if they are located in the corresponding position i.e. A[i][j] can only be swapped with B[i][j]. If possible then print Yes otherwise, No.Examples: Input: A[][] = {{2, 10}, B
7 min read
Program to concatenate two given Matrices of same size
Given two matrices A and B of size M x N, the task is to concatenate them into one matrix.Concatenation of matrix: The process of appending elements of every row of the matrix one after the other is known as the Concatenation of matrix. Examples: Input: A[][] = {{1, 2}, {3, 4}}, B[][] = {{5, 6}, {7, 8}} Output: 1 2 5 6 3 4 7 8 Explanation: Elements
6 min read
Maximize count of indices with same element by pairing rows from given Matrices
Given two 2D binary arrays, a[][] and b[][] both of size M*N, the task is to pair each row in the array a[][] with any row in the array b[][] such that the total score can be maximized and the score for each pair is calculated as the total indexes at which values of both rows are identical. Note: Each row of the array b[][] can only be paired with
15+ min read
Maximize the cell-wise product of Matrices
Given two matrices M1[][] and M2[][] of size R * C along with an integer X. In one operation select any cell of M1 let's say M1[ i ][ j ] and update it as M1[ i ][ j ] +1 or M1[ i ][ j ] - 1, Then the task is to maximize the cell-wise product of elements by using the given operation X times. (Formally, ∑M1[ i ][ j ] * M2[ i ][ j ] for (1 â‰Ī i â‰Ī R),
10 min read
Program for addition of two matrices
Given two N x M matrices. Find a N x M matrix as the sum of given matrices each value at the sum of values of corresponding elements of the given two matrices. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: Below is the idea to solve the problem. Iterate over every cell of matrix (i, j), add the corres
7 min read
Program to check if two given matrices are identical
The below program checks if two square matrices of size 4*4 are identical or not. For any two matrices to be equal, a number of rows and columns in both the matrix should be equal and the corresponding elements should also be equal. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Implementation: C/C++ Code // C++
6 min read
Kronecker Product of two matrices
Given an m*n matrix A and a p*q matrix B, their Kronecker product C = A tensor B, also called their matrix direct product, is a (m*p) * (n*q) matrix. A tensor B = |a11B a12B| |a21B a22B| = |a11b11 a11b12 a12b11 a12b12| |a11b21 a11b22 a12b21 a12b22| |a11b31 a11b32 a12b31 a12b32| |a21b11 a21b12 a22b11 a22b12| |a21b21 a21b22 a22b21 a22b22| |a21b31 a21
10 min read
Test Case Generation | Set 1 (Random Numbers, Arrays and Matrices)
The test cases are an extremely important part of any "Software/Project Testing Process". Hence this Set will be very important for all aspiring software developers. The following are the programs to generate test cases. Generating Random Numbers C/C++ Code // A C++ Program to generate test cases for // random number #include<bits/stdc++.h> u
12 min read
Maximum image overlap on given binary Matrices
Given two images represented as binary square matrices, matrix1[] and matrix2[] of size n x n, the task is to find the largest possible overlap of 1 in both matrices by translating one matrix over other any number of times to left, right, up, and/or down without any rotation. Note: Any 1-bit translated outside the matrix borders is erased. Examples
12 min read
Check matrix transformation by flipping sub-matrices along the principal or anti-diagonal
Given two matrices mat1[][] and mat2[][] of size N*M, the task is check if it is possible to transform mat1 into mat2 by selecting any square sub-matrix from mat1 and flipping it along its principal diagonal or anti-diagonal. Examples: Input: N = 2, M = 3, mat1[][] = {{1, 2, 3}, {4, 5, 6}}, mat2[][] = {{1, 4, 3}, {6, 5, 2}}Output: YESExplanation: I
13 min read