The Wayback Machine - https://web.archive.org/web/20240907033929/https://www.geeksforgeeks.org/cholesky-decomposition-matrix-decomposition/
Open In App

Cholesky Decomposition : Matrix Decomposition

Last Updated : 20 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Basic
46.94%
24.1K

In linear algebra, a matrix decomposition or matrix factorization is a factorization of a matrix into a product of matrices. There are many different matrix decompositions. One of them is Cholesky Decomposition.

The Cholesky decomposition or Cholesky factorization is a decomposition of a Hermitian, positive-definite matrix into the product of a lower triangular matrix and its conjugate transpose. The Cholesky decomposition is roughly twice as efficient as the LU decomposition for solving systems of linear equations.

The Cholesky decomposition of a Hermitian positive-definite matrix A is a decomposition of the form A = [L][L]T, where L is a lower triangular matrix with real and positive diagonal entries, and LT denotes the conjugate transpose of L. Every Hermitian positive-definite matrix (and thus also every real-valued symmetric positive-definite matrix) has a unique Cholesky decomposition.

\left[\begin{array}{lll} A_{00} & A_{01} & A_{02} \\ A_{10} & A_{11} & A_{12} \\ A_{20} & A_{21} & A_{22} \end{array}\right]=\left[\begin{array}{lll} L_{00} & 0 & 0 \\ L_{10} & L_{11} & 0 \\ L_{20} & L_{21} & L_{22} \end{array}\right]\left[\begin{array}{ccc} L_{00} & L_{10} & L_{20} \\ 0 & L_{11} & L_{21} \\ 0 & 0 & L_{22} \end{array}\right]
 

Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L LT 

The following formulas are obtained by solving above lower triangular matrix and its transpose. These are the basis of Cholesky Decomposition Algorithm : 

L_{j,j}=\sqrt {A_{j,j}-\sum_{k=0}^{j-1}(L_{j,k})^{2}}
 

Example : 

Input : 

\left[\begin{array}{ccc} 4 & 12 & -16 \\ 12 & 37 & -43 \\ -16 & -43 & 98 \end{array}\right]

Output :

\left[\begin{array}{ccc} 2 & 0 & 0 \\ 6 & 1 & 0 \\ -8 & 5 & 3 \end{array}\right]\left[\begin{array}{ccc} 2 & 6 & -8 \\ 0 & 1 & 5 \\ 0 & 0 & 3 \end{array}\right]

Below is the implementation of Cholesky Decomposition.  

C++

// CPP program to decompose a matrix using
// Cholesky Decomposition
#include <bits/stdc++.h>
using namespace std;
 
const int MAX = 100;
 
void Cholesky_Decomposition(int matrix[][MAX],
                                      int n)
{
    int lower[n][n];
    memset(lower, 0, sizeof(lower));
 
    // Decomposing a matrix into Lower Triangular
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++) {
            int sum = 0;
 
            if (j == i) // summation for diagonals
            {
                for (int k = 0; k < j; k++)
                    sum += pow(lower[j][k], 2);
                lower[j][j] = sqrt(matrix[j][j] -
                                        sum);
            } else {
 
                // Evaluating L(i, j) using L(j, j)
                for (int k = 0; k < j; k++)
                    sum += (lower[i][k] * lower[j][k]);
                lower[i][j] = (matrix[i][j] - sum) /
                                      lower[j][j];
            }
        }
    }
 
    // Displaying Lower Triangular and its Transpose
    cout << setw(6) << " Lower Triangular" 
         << setw(30) << "Transpose" << endl;
    for (int i = 0; i < n; i++) {
         
        // Lower Triangular
        for (int j = 0; j < n; j++)
            cout << setw(6) << lower[i][j] << "\t";
        cout << "\t";
         
        // Transpose of Lower Triangular
        for (int j = 0; j < n; j++)
            cout << setw(6) << lower[j][i] << "\t";
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    int n = 3;
    int matrix[][MAX] = { { 4, 12, -16 },
                        { 12, 37, -43 },
                        { -16, -43, 98 } };
    Cholesky_Decomposition(matrix, n);
    return 0;
}

                    

Java

// Java program to decompose
// a matrix using Cholesky
// Decomposition
 
class GFG {
 
    // static int MAX = 100;
    static void Cholesky_Decomposition(int[][] matrix,
                                       int n)
    {
        int[][] lower = new int[n][n];
 
        // Decomposing a matrix
        // into Lower Triangular
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= i; j++) {
                int sum = 0;
 
                // summation for diagonals
                if (j == i) {
                    for (int k = 0; k < j; k++)
                        sum += (int)Math.pow(lower[j][k],
                                             2);
                    lower[j][j] = (int)Math.sqrt(
                        matrix[j][j] - sum);
                }
 
                else {
 
                    // Evaluating L(i, j)
                    // using L(j, j)
                    for (int k = 0; k < j; k++)
                        sum += (lower[i][k] * lower[j][k]);
                    lower[i][j] = (matrix[i][j] - sum)
                                  / lower[j][j];
                }
            }
        }
 
        // Displaying Lower
        // Triangular and its Transpose
        System.out.println(" Lower Triangular\t Transpose");
        for (int i = 0; i < n; i++) {
 
            // Lower Triangular
            for (int j = 0; j < n; j++)
                System.out.print(lower[i][j] + "\t");
            System.out.print("");
 
            // Transpose of
            // Lower Triangular
            for (int j = 0; j < n; j++)
                System.out.print(lower[j][i] + "\t");
            System.out.println();
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 3;
        int[][] matrix = new int[][] { { 4, 12, -16 },
                                       { 12, 37, -43 },
                                       { -16, -43, 98 } };
 
        Cholesky_Decomposition(matrix, n);
    }
}
 
// This code is contributed by mits

                    

Python3

# Python3 program to decompose
# a matrix using Cholesky
# Decomposition
import math
MAX = 100;
 
def Cholesky_Decomposition(matrix, n):
 
    lower = [[0 for x in range(n + 1)]
                for y in range(n + 1)];
 
    # Decomposing a matrix
    # into Lower Triangular
    for i in range(n):
        for j in range(i + 1):
            sum1 = 0;
 
            # summation for diagonals
            if (j == i):
                for k in range(j):
                    sum1 += pow(lower[j][k], 2);
                lower[j][j] = int(math.sqrt(matrix[j][j] - sum1));
            else:
                 
                # Evaluating L(i, j)
                # using L(j, j)
                for k in range(j):
                    sum1 += (lower[i][k] *lower[j][k]);
                if(lower[j][j] > 0):
                    lower[i][j] = int((matrix[i][j] - sum1) /
                                               lower[j][j]);
 
    # Displaying Lower Triangular
    # and its Transpose
    print("Lower Triangular\t\tTranspose");
    for i in range(n):
         
        # Lower Triangular
        for j in range(n):
            print(lower[i][j], end = "\t");
        print("", end = "\t");
         
        # Transpose of
        # Lower Triangular
        for j in range(n):
            print(lower[j][i], end = "\t");
        print("");
 
# Driver Code
n = 3;
matrix = [[4, 12, -16],
          [12, 37, -43],
          [-16, -43, 98]];
Cholesky_Decomposition(matrix, n);
 
# This code is contributed by mits

                    

C#

// C# program to decompose
// a matrix using Cholesky
// Decomposition
using System;
 
class GFG {
 
    // static int MAX = 100;
    static void Cholesky_Decomposition(int[, ] matrix,
                                       int n)
    {
        int[, ] lower = new int[n, n];
 
        // Decomposing a matrix
        // into Lower Triangular
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= i; j++) {
                int sum = 0;
 
                // summation for diagonals
                if (j == i) {
                    for (int k = 0; k < j; k++)
                        sum += (int)Math.Pow(lower[j, k],
                                             2);
                    lower[j, j] = (int)Math.Sqrt(
                        matrix[j, j] - sum);
                }
 
                else {
 
                    // Evaluating L(i, j)
                    // using L(j, j)
                    for (int k = 0; k < j; k++)
                        sum += (lower[i, k] * lower[j, k]);
                    lower[i, j] = (matrix[i, j] - sum)
                                  / lower[j, j];
                }
            }
        }
 
        // Displaying Lower
        // Triangular and its Transpose
        Console.WriteLine(
            "  Lower Triangular\t   Transpose");
        for (int i = 0; i < n; i++) {
 
            // Lower Triangular
            for (int j = 0; j < n; j++)
                Console.Write(lower[i, j] + "\t");
            Console.Write("");
 
            // Transpose of
            // Lower Triangular
            for (int j = 0; j < n; j++)
                Console.Write(lower[j, i] + "\t");
            Console.WriteLine();
        }
    }
 
    // Driver Code
    static int Main()
    {
        int n = 3;
        int[, ] matrix = { { 4, 12, -16 },
                           { 12, 37, -43 },
                           { -16, -43, 98 } };
 
        Cholesky_Decomposition(matrix, n);
        return 0;
    }
}
 
// This code is contributed by mits

                    

PHP

<?php
// PHP program to decompose
// a matrix using Cholesky
// Decomposition
$MAX = 100;
 
function Cholesky_Decomposition($matrix, $n)
{
    $lower;
    for ($i = 0; $i <= $n; $i++)
    for ($j = 0; $j <= $n; $j++)
    $lower[$i][$j] = 0;
 
    // Decomposing a matrix
    // into Lower Triangular
    for ($i = 0; $i < $n; $i++)
    {
        for ($j = 0; $j <= $i; $j++)
        {
            $sum = 0;
 
            // summation for diagonals
            if ($j == $i)
            {
                for ($k = 0; $k < $j; $k++)
                    $sum += pow($lower[$j][$k], 2);
                $lower[$j][$j] = sqrt($matrix[$j][$j] -
                                      $sum);
            }
            else
            {
                // Evaluating L(i, j)
                // using L(j, j)
                for ($k = 0; $k < $j; $k++)
                    $sum += ($lower[$i][$k] *
                             $lower[$j][$k]);
                $lower[$i][$j] = ($matrix[$i][$j] - $sum) /
                                  $lower[$j][$j];
            }
        }
    }
 
    // Displaying Lower Triangular
    // and its Transpose
    echo "     Lower Triangular" .
           str_pad("Transpose", 30, " ",
                   STR_PAD_BOTH) . "\n";
    for ($i = 0; $i < $n; $i++)
    {
         
        // Lower Triangular
        for ($j = 0; $j < $n; $j++)
            echo str_pad($lower[$i][$j], 6,
                         " ", STR_PAD_BOTH)."\t";
        echo "\t";
         
        // Transpose of
        // Lower Triangular
        for ($j = 0; $j < $n; $j++)
            echo str_pad($lower[$j][$i], 6,
                         " ", STR_PAD_BOTH)."\t";
        echo "\n";
    }
}
 
// Driver Code
$n = 3;
$matrix = array(array(4, 12, -16),
                array(12, 37, -43),
                array(-16, -43, 98));
Cholesky_Decomposition($matrix, $n);
 
// This code is contributed by vt_m.
?>

                    

Javascript

<script>
// javascript program to decompose
// a matrix using Cholesky
// Decomposition
   // function MAX = 100;
function Cholesky_Decomposition(matrix,n)
{
    var lower = Array(n).fill(0).map(x => Array(n).fill(0));
 
    // Decomposing a matrix
    // into Lower Triangular
    for (var i = 0; i < n; i++) {
        for (var j = 0; j <= i; j++) {
            var sum = 0;
 
            // summation for diagonals
            if (j == i) {
                for (var k = 0; k < j; k++)
                    sum += parseInt(Math.pow(lower[j][k],
                                         2));
                lower[j][j] = parseInt(Math.sqrt(
                    matrix[j][j] - sum));
            }
 
            else {
 
                // Evaluating L(i, j)
                // using L(j, j)
                for (var k = 0; k < j; k++)
                    sum += (lower[i][k] * lower[j][k]);
                lower[i][j] = (matrix[i][j] - sum)
                              / lower[j][j];
            }
        }
    }
 
    // Displaying Lower
    // Triangular and its Transpose
    document.write(" Lower Triangular     Transpose<br>");
    for (var i = 0; i < n; i++) {
 
        // Lower Triangular
        for (var j = 0; j < n; j++)
            document.write(lower[i][j] + "        ");
         
 
        // Transpose of
        // Lower Triangular
        for (var j = 0; j < n; j++)
            document.write(lower[j][i] + "        ");
        document.write('<br>');
    }
}
 
// Driver Code
var n = 3;
var matrix = [[ 4, 12, -16 ],
                               [ 12, 37, -43 ],
                               [ -16, -43, 98 ] ];
 
Cholesky_Decomposition(matrix, n);
 
// This code contributed by Princi Singh
</script>

                    

Output
 Lower Triangular                     Transpose
     2         0         0             2         6        -8    
     6         1         0             0         1         5    
    -8         5         3             0         0         3    

Time Complexity: O(n^3)
Auxiliary Space: O(n^2)

 



Similar Reads

Calculate sum in Diagonal Matrix Decomposition by removing elements in L-shape
Given two integers N representing the dimension of a square matrix and an integer A with which the matrix is initialized. Given another integer mod. Calculate the required sum by following the given steps: Select the product of all elements in L shape beginning from the topmost right element, add it to the sum and remove all of them from the matrix
6 min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Sum of decomposition values of all suffixes of an Array
Given an array arr[], the task is to find the sum of the decomposition value of the suffixes subarray.Decomposition Value: The decomposition value of a subarray is the count of the partition in the subarray possible. The partition in the array at index [Tex]i [/Tex]can be done only if the elements of the array before if it less than the current ind
8 min read
K-shell decomposition on Social Networks
Prerequisite: Introduction to Social Networks K-shell decomposition is the method in which we can divide nodes on the basis of the number of its degree like nodes with degree 1 in one bucket etc. Consider an example, assume there are n nodes and you apply k-shell decomposition in it. So nodes with degree 1 will be in bucket1 then we will see that a
4 min read
MO's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction)
Let us consider the following problem to understand MO's Algorithm.We are given an array and a set of query ranges, we are required to find the sum of every query range. Example: Input: arr[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; query[] = [0, 4], [1, 3] [2, 4] Output: Sum of arr[] elements in range [0, 4] is 8 Sum of arr[] elements in range [1, 3] is 4 S
15+ min read
Range Minimum Query (Square Root Decomposition and Sparse Table)
We have an array arr[0 . . . n-1]. We should be able to efficiently find the minimum value from index L (query start) to R (query end) where 0 &lt;= L &lt;= R &lt;= n-1. Consider a situation when there are many range queries. Example: Input: arr[] = {7, 2, 3, 0, 5, 10, 3, 12, 18}; query[] = [0, 4], [4, 7], [7, 8]Output: Minimum of [0, 4] is 0 Minim
15+ min read
Introduction to Heavy Light Decomposition
Heavy Light decomposition (HLD) is one of the most used techniques in competitive programming. Example Problem: Let us understand Heavy-light decomposition (HLD) with the help of below example. Suppose we have an unbalanced tree (not necessarily a Binary Tree) of n nodes, and we have to perform operations on the tree to answer a number of queries,
4 min read
Centroid Decomposition of Tree
Background : What is centroid of Tree? Centroid of a Tree is a node which if removed from the tree would split it into a ‘forest’, such that any tree in the forest would have at most half the number of vertices in the original tree. Suppose there are n nodes in the tree. ‘Subtree size’ for a node is the size of the tree rooted at the node. Let S(v)
15+ min read
Square Root (Sqrt) Decomposition Algorithm
Square Root Decomposition Technique is one of the most common query optimization techniques used by competitive programmers. This technique helps us to reduce Time Complexity by a factor of sqrt(N) The key concept of this technique is to decompose a given array into small chunks specifically of size sqrt(N) Follow the below steps to solve the probl
15+ min read
Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in O(sqrt(height)) time)
Prerequisite: Introduction and DFSThe task is to find LCA of two given nodes in a tree (not necessarily a Binary Tree). In previous posts, we have seen how to calculate LCA using the Sparse Matrix DP approach. In this post, we will see an optimization done on the Naive method by sqrt decomposition technique that works well over the Naive Approach.
15+ min read
Implementation of Heavy Light Decomposition
We strongly recommend to refer below post as a prerequisite of this.Heavy Light Decomposition | Set 1 (Introduction)In the above post, we discussed the Heavy-light decomposition (HLD) with the help of below example. Suppose we have an unbalanced tree (not necessarily a Binary Tree) of n nodes, and we have to perform operations on the tree to answer
15+ min read
Doolittle Algorithm | LU Decomposition
Doolittle Algorithm: The Doolittle Algorithm is a method for performing LU Decomposition, where a given matrix is decomposed into a lower triangular matrix L and an upper triangular matrix U. This decomposition is widely used in solving systems of linear equations, inverting matrices, and computing determinants. LU DecompositionLet A be a square ma
11 min read
LU Decomposition
LU decomposition of a matrix is the factorization of a given square matrix into two triangular matrices, one upper triangular matrix and one lower triangular matrix, such that the product of these two matrices gives the original matrix. It was introduced by Alan Turing in 1948, who also created the Turing machine. LU Decomposition is a fundamental
7 min read
Singular Value Decomposition (SVD)
The Singular Value Decomposition (SVD) of a matrix is a factorization of that matrix into three matrices. It has some interesting algebraic properties and conveys important geometrical and theoretical insights about linear transformations. It also has some important applications in data science. In this article, I will try to explain the mathematic
6 min read
Check if it is possible to make the given matrix increasing matrix or not
Given a matrix of N X M of positive integers, the task is to find out whether it is possible to make the matrix increasing or not. Print the matrix constructed otherwise print -1. Matrix elements should be greater than zero. A matrix is said to be increasing matrix if: For each row, the elements are in the increasing order.For each column, the elem
10 min read
Program to check if a matrix is Binary matrix or not
Given a matrix, the task is to check if that matrix is a Binary Matrix. A Binary Matrix is a matrix in which all the elements are either 0 or 1. It is also called Logical Matrix, Boolean Matrix, Relation Matrix. Examples: Input: {{1, 0, 1, 1}, {0, 1, 0, 1} {1, 1, 1, 0}} Output: Yes Input: {{1, 0, 1, 1}, {1, 2, 0, 1}, {0, 0, 1, 1}} Output: No Approa
5 min read
Program to convert given Matrix to a Diagonal Matrix
Given a N*N matrix. The task is to convert the matrix to a diagonal matrix. That is to change the values of the non-diagonal elements of a matrix to 0.Diagonal-Matrix: A matrix is called a Diagonal Matrix if all the non-diagonal elements of the matrix are zero.Examples: Input : mat[][] = {{ 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 }} Output : {{2, 0, 7},
8 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
Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B
Given two binary matrices, A[][] and B[][] of size N×M, the task is to find the minimum number of swaps of the elements of matrix A, needed to convert matrix A into matrix B. If it is impossible to do so then print "-1". Examples : Input: A[][] = {{1, 1, 0}, {0, 0, 1}, {0, 1, 0}}, B[][] = {{0, 0, 1}, {0, 1, 0}, {1, 1, 0}}Output: 3Explanation: One p
8 min read
Minimum number of steps to convert a given matrix into Upper Hessenberg matrix
Given a matrix of order NxN, Find the minimum number of steps to convert the given matrix into the Upper Hessenberg matrix. In each step, the only operation allowed is to decrease or increase any element value by 1.Examples: Input : N=3 1 2 8 1 3 4 2 3 4 Output :2 Decrease the element a[2][0] 2 times. Now the matrix is upper hessenbergInput : N=4 1
4 min read
Minimum steps required to convert the matrix into lower hessenberg matrix
Given a matrix of order NxN, Find the minimum number of steps to convert given matrix into Lower Hessenberg matrix. In each step, the only operation allowed is to decrease or increase any element value by 1.Examples: Input: mat[][] = { {1, 2, 8}, {1, 3, 4}, {2, 3, 4}} Output: 8 Decrease the element a[0][2] 8 times. Now the matrix is lower Hessenber
4 min read
Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
Given a matrix of order NxN, the task is to find the minimum number of steps to convert given matrix into Diagonally Dominant Matrix. In each step, the only operation allowed is to decrease or increase any element by 1.Examples: Input: mat[][] = {{3, 2, 4}, {1, 4, 4}, {2, 3, 4}} Output: 5 Sum of the absolute values of elements of row 1 except the d
6 min read
Maximize Matrix sum by replacing 0s such that Matrix remains sorted
Given a matrix mat[][] of dimension N*M which is sorted row-wise and column-wise, the task is to find the sum of the elements of the matrix by replacing all 0s in the matrix with any value such that the matrix remains sorted row-wise and column-wise. If it is not possible, then print "-1". Note: 0s will be only present in internal cells. i.e., neit
7 min read
Check if a given matrix can be converted to another given matrix by row and column exchanges
Given a matrix startMatrix and another matrix finalMatrix, the task is to check if startMatrix can be converted to finalMatrix by column exchanges and a row exchanges. Examples: Input: start[][] = {{1, 2, 3, 4}, {5, 6, 7, 8} {9, 10, 11, 12}, {13, 14, 15, 16}}final[][] = {{1, 4, 3, 2}, {5, 8, 7, 6}, {13, 16, 15, 14}, {9, 12, 11, 10}} Output: Yes Exp
9 min read
Create matrix whose sum of diagonals in each sub matrix is even
Given a number N, the task is to create a square matrix of size N*N with values in range [1, N*N], such that the sum of each diagonal of an even sub-square matrix is even. Examples: Input: N = 3Output: 1 2 3 4 5 6 7 8 9 Explanation:For each even sub-square matrix the sum of each diagonal is a even number.1 2 4 5 sum of each diagonal is 6 and 6 i.e
5 min read
Construct a square Matrix whose parity of diagonal sum is same as size of matrix
Given an integer N representing the size of the matrix, the task is to construct a square matrix N * N which have an element from 1 to N2 such that the parity of the sum of its diagonals is equal to the parity of integer N. Examples: Input: N = 4Output:1 2 3 4 8 7 6 59 10 11 1216 15 14 13Explanation:Sum of diagonal = 32 and 36 and integer N = 4, al
6 min read
Minimize count of adjacent row swaps to convert given Matrix to a Lower Triangular Matrix
Given a matrix, mat[][] of size N × N, the task is to minimize the count of adjacent row swaps to convert the given matrix to a lower triangular matrix. If it is not possible to convert the given matrix to a lower triangular matrix, then print -1. Note: A lower triangular matrix contains 0s at all the indices above the main diagonal. Examples: Inpu
9 min read
Count right angled triangles in a matrix having two of its sides parallel to sides of the matrix
Given a binary matrix arr[][] of dimensions N * M , the task is to count the number of right-angled triangles that can be formed by joining the cells containing the value 1 such that the triangles must have any two of its sides parallel to the sides of the rectangle. Examples: Input: arr[][] = {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}Output: 4Explanation:
8 min read
Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix
Given a matrix arr[][] of dimensions N * M, the task is to generate a matrix such that any cell (r, c) stores the sum of adjacent elements present horizontally, vertically, and diagonally in the given matrix. Examples: Input: arr[][] = {{1, 3}, {2, 4}}Output: {{9, 7}, {8, 6}}Explanation: Matrix is constructed by the following operations: For cell (
9 min read
Article Tags :
Practice Tags :