Adding two matrices

PHOTO EMBED

Tue Feb 08 2022 08:09:29 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #2d #array #matrix #addition #practice

class Solution
{
    //Function to add two matrices.
    static int[][] sumMatrix(int A[][], int B[][])
    {
        int n = A.length, m = A[0].length;
        int res[][] = new int[0][0];
        //Check if two input matrix are of different dimensions
        if(n != B.length || m != B[0].length)
            return res;
        
        res = new int[n][m];
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                res[i][j] = A[i][j] + B[i][j];
                
        return res;
    }
}
content_copyCOPY

Adding two matrices The Addition is one of the easiest operations to carry out. The same holds true for matrices. Two matrices can be added only if they have the same dimensions. The elements at similar positions get added. Given two matrices A and B having (n1 x m1) and (n2 x m2) dimensions respectively. Add A and B. Example 1: Input: n1 = 2, m1 = 3 A[][] = {{1, 2, 3}, {4, 5, 6}} n2 = 2, m2 = 3 B[][] = {{1, 3, 3}, {2, 3, 3}} Output: 2 5 6 6 8 9 Explanation: The summation matrix of A and B is: res[][] = {{2, 5, 6}, {6, 8, 9}} The output is generated by traversing each row sequentially. Example 2: Input: n1 = 3, m1 = 2 A[][] = {{1, 2}, {3, 4}, {5, 6}} n2 = 3, m2 = 2 B[][] = {{1, 3}, {3, 2}, {3, 3}} Output: 2 5 6 6 8 9 Your Task: You don't need to read input or print anything. Complete the function sumMatrix() that takes A and B as input parameters and returns a matrix containing their sum. If the addition is not possible return an empty matrix (of size zero). Expected Time Complexity: O(n1 * m1) Expected Auxiliary Space: O(n1 * m1) for the resultant matrix only. Constraints: 1 <= n1, m1, n2, m2 <= 30 0 <= Ai, Bi <= 100

https://practice.geeksforgeeks.org/problems/adding-two-matrices3512/1/?track=DSASP-Matrix&batchId=190