# 311.Sparse-Matrix-Multiplication

## 311. Sparse Matrix Multiplication

## 题目地址

<https://leetcode.com/problems/sparse-matrix-multiplication/>

## 题目描述

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

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

Example:

Input:

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

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

Output:

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

## 代码

### Approach #1

```java
class Solution {
  public int[][] multiply(int[][] A, int[][] B) {
        int m = A.length, n = A[0].length;
    int nB = B[0].length;
    int[][] C = new int[m][nB];

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

    return C;
  }
}
```

```java
class Solution {
  public int[][] multiply(int[][] A, int[][] B) {
    int m = A.length, n = A[0].length, nB = B[0].length;
    int[][] C = new int[m][nB];

    for (int i = 0; i < m; i++) {
      for (int j = 0; j < nB; j++) {
          for (int k = 0; k < n; k++) {
            C[i][j] += A[i][k] * B[k][j];
          }
      }
    }
    return C;  
  }
}
```


---

# 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://wentao-shao.gitbook.io/leetcode/matrix/311.sparse-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.
