Array ( [0] => [1] => questions [2] => Arrays [3] => Multiplication-of-two-matrixes ) Arrays | Multiplication of two matrixes | THE INQUISITIVE





Multiplication of two matrixes

LEVEL:Beginner

Description

Given two 2D sets of elements representing of M*N multidimensional array. You have to perform multiplication operation between the two arrays. Note: Check whether it’s possible or not

Input Format

First line contains two integers M and N. Next M lines contains N integers separated by spaces representing matrix1. Next M lines contains N integers separated by spaces representing matrix2.

Output Format

Print the resultant 2D array.


Example 1:

Input
3 3
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
7 8 9

Output
30 36 42
66 83 96
102 126 150
Example 2:

Input
2 2
1 2 
3 4
1 2
3 4
Output
7 10
15 22
Example 3:

Input
3 3
3 2 1
6 5 4
9 8 7
3 2 1
6 5 4
9 8 7

Output
42 24 18
84 69 54
138 114 90

oops

Login to see Discussion




Approach


Step-i) first check if number of coloums of first matrix is equal to number of rows of second matrix or not
Step-ii) if it's not return "Multiplication is not possible"
Step-iii) create an array of size col_1 * row_3 (here string has been used just for sake of simplicity of printing in main method
without any loops
Step-iv) run a loop from c=0 to cStep-v) in that loop run another loop from d=0 to dStep-vi) initialize sum to zero
Step-vii)run another loop from k = 0 to k< row_2
Step-viii) multiply A[c][k] and B[k][d] and add it to sum
Step-ix) assign sum to cth row and dth col of created array
Step-x) return the array

Time Complexity: O(n^3)
Space Complexity: O(m*n) where m is number of colums of first matrix and n is number of rows of second matrix


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution