# 311\_Sparse Matrix Multiplication

Given two [sparse matrices](https://en.wikipedia.org/wiki/Sparse_matrix) **A** and **B**, return the result of **AB**.

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

**Example:**

```
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 |
```

## Solution 1: Only do the calculation for non-zero elements in A

```python
class Solution(object):
    def multiply(self, A, B):
        """
        :type A: List[List[int]]
        :type B: List[List[int]]
        :rtype: List[List[int]]
        """
        rowA = len(A)
        colA = len(A[0])
        colB = len(B[0])
        ret = [[0 for column in range(colB)] for row in range(rowA)]
        for i in range(rowA):
            for j in range(colA):
                if A[i][j] != 0:
                    for k in range(colB):
                        ret[i][k] += A[i][j] * B[j][k]
        return ret
```

## Solution 2. Using dictionary to store non-zero elements in A

```python
class Solution(object):
    def multiply(self, A, B):
        """
        :type A: List[List[int]]
        :type B: List[List[int]]
        :rtype: List[List[int]]
        """
        m = len(A)
        l = len(A[0])
        n = len(B[0])
        ret = [[0 for col in range(n)] for row in range(m)]
        dic = {}
        # final all nonzero elements in A
        for i in range(m):
            tmp = {}
            for j in range(l):
                if A[i][j] != 0:
                    tmp[j] = A[i][j]
            dic[i] = tmp
        # compute matrix multiplication
        for i in range(m):
            tmp = dic.get(i)
            for j, val in tmp.items():
                for k in range(n):
                    ret[i][k] += val * B[j][k]
        return ret
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lei-d.gitbook.io/leetcode/matrix/311sparse-matrix-multiplication.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
