 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sparse Matrix Multiplication in C++
Suppose we have two matrices A and B, we have to find the result of AB. We may assume that A's column number is equal to B's row number.
So, if the input is like [[1,0,0],[-1,0,3]] [[7,0,0],[0,0,0],[0,0,1]],
| 1 | 0 | 0 | 
| -1 | 0 | 3 | 
| 7 | 0 | 0 | 
| 0 | 0 | 0 | 
| 0 | 0 | 1 | 
then the output will be [[7,0,0],[-7,0,3]]
| 7 | 0 | 0 | 
| -7 | 0 | 3 | 
To solve this, we will follow these steps −
- r1 := size of A, r2 := size of B 
- c1 := size of A[0], c2 := size of B[0] 
- Define one 2D array ret of order r1 x c2 
- Define an array sparseA[r1] of pairs 
-  for initialize i := 0, when i < r1, update (increase i by 1), do − -  for initialize j := 0, when j < c1, update (increase j by 1), do − -  if A[i, j] is not equal to 0, then − - insert { j, A[i, j] } at the end of sparseA[i] 
 
 
-  
 
-  
-  for initialize i := 0, when i < r1, update (increase i by 1), do − -  for initialize j := 0, when j < size of sparseA[i], update (increase j by 1), do − -  for initialize k := 0, when k < c2, update (increase k by 1), do − - x := first element of sparseA[i, j] 
-  if B[x, k] is not equal to 0, then − - ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k] 
 
 
 
-  
 
-  
- return ret 
Example
Let us see the following implementation to get better understanding −
class Solution { public:    vector<vector<int<> multiply(vector<vector<int<>& A, vector<vector<int<>& B) {       int r1 = A.size();       int r2 = B.size();       int c1 = A[0].size();       int c2 = B[0].size();       vector < vector <int< > ret(r1, vector <int< (c2));       vector < pair <int, int> > sparseA[r1];       for(int i = 0; i < r1; i++){          for(int j = 0; j < c1; j++){             if(A[i][j] != 0)sparseA[i].push_back({j, A[i][j]});          }       }       for(int i = 0; i < r1; i++){          for(int j = 0; j < sparseA[i].size(); j++){             for(int k = 0; k < c2; k++){                int x = sparseA[i][j].first;                if(B[x][k] != 0){                   ret[i][k] += sparseA[i][j].second * B[x][k];                }             }          }       }       return ret;    } };  Input
{{1,0,0},{-1,0,3}},{{7,0,0},{0,0,0},{0,0,1}} Output
[[7, 0, 0, ],[-7, 0, 3, ],]
