# [LeetCode] 311. Sparse Matrix Multiplication 稀疏矩阵相乘

2021年09月15日 阅读数：1

Given two sparse matrices A and B, return the result of AB.html

You may assume that A's column number is equal to B's row number.java

Example:python

```A = [
[ 1, 0, 0],
[-1, 0, 3]
]

B = [
[ 7, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 1 ]
]

|  1 0 0 |   | 7 0 0 |   |  7 0 0 |
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
| 0 0 1 |```

Java: naive solution. T: O(n^3)优化

```public int[][] multiply(int[][] A, int[][] B) {
//validity check
int[][] C = new int[A.length][B[0].length];

for(int i=0; i<C.length; i++){
for(int j=0; j<C[0].length; j++){
int sum=0;
for(int k=0; k<A[0].length; k++){
sum += A[i][k]*B[k][j];
}
C[i][j] = sum;
}
}

return C;
}
```

Java:url

```public int[][] multiply(int[][] A, int[][] B) {
//validity check
int[][] C = new int[A.length][B[0].length];

for(int i=0; i<C.length; i++){
for(int k=0; k<A[0].length; k++){
if(A[i][k]!=0){
for(int j=0; j<C[0].length; j++){
C[i][j] += A[i][k]*B[k][j];
}
}
}
}

return C;
}
```

Python: optimized, T: O(n^2)spa

```# Time:  O(m * n * l), A is m x n matrix, B is n x l matrix
# Space: O(m * l)
class Solution(object):
def multiply(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
m, n, l = len(A), len(A[0]), len(B[0])
res = [[0 for _ in xrange(l)] for _ in xrange(m)]
for i in xrange(m):
for k in xrange(n):
if A[i][k]:
for j in xrange(l):
res[i][j] += A[i][k] * B[k][j]
return res　　```

C++:htm

```class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
vector<vector<int>> res(A.size(), vector<int>(B[0].size()));
for (int i = 0; i < A.size(); ++i) {
for (int k = 0; k < A[0].size(); ++k) {
if (A[i][k] != 0) {
for (int j = 0; j < B[0].size(); ++j) {
if (B[k][j] != 0) res[i][j] += A[i][k] * B[k][j];
}
}
}
}
return res;
}
};
```

C++:

```class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
vector<vector<int>> res(A.size(), vector<int>(B[0].size()));
vector<vector<pair<int, int>>> v(A.size(), vector<pair<int,int>>());
for (int i = 0; i < A.size(); ++i) {
for (int k = 0; k < A[i].size(); ++k) {
if (A[i][k] != 0) v[i].push_back({k, A[i][k]});
}
}
for (int i = 0; i < A.size(); ++i) {
for (int k = 0; k < v[i].size(); ++k) {
int col = v[i][k].first;
int val = v[i][k].second;
for (int j = 0; j < B[0].size(); ++j) {
res[i][j] += val * B[col][j];
}
}
}
return res;
}
};
```