# 0311. Sparse Matrix Multiplication

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

## Description

Given two [sparse matrices](https://en.wikipedia.org/wiki/Sparse_matrix) `mat1` of size `m x k` and `mat2` of size `k x n`, return the result of `mat1 x mat2`. You may assume that multiplication is always possible.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/03/12/mult-grid.jpg)

```
**Input:** mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
**Output:** [[7,0,0],[-7,0,3]]
```

**Example 2:**

```
**Input:** mat1 = [[0]], mat2 = [[0]]
**Output:** [[0]]
```

**Constraints:**

* `m == mat1.length`
* `k == mat1[i].length == mat2.length`
* `n == mat2[i].length`
* `1 <= m, n, k <= 100`
* `-100 <= mat1[i][j], mat2[i][j] <= 100`

## ac

math problem.

```java
class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        // edge cases
        if (A.length == 0 || A[0].length == 0 || B.length == 0 || B[0].length == 0)
            return new int[0][0];

        int rowa = A.length, cola = A[0].length, rowb = B.length, colb = B[0].length;
        int[][] res = new int[rowa][colb];

        for (int ra = 0; ra < rowa; ra++) {
            for (int ca = 0; ca < cola; ca++) {
                if (A[ra][ca] == 0) continue; // skip 0
                for (int cb = 0; cb < colb; cb++) {
                    res[ra][cb] += A[ra][ca] * B[ca][cb];
                }
            }
        }

        return res;
    }
}

/*
know how to do the math
*/
```


---

# 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://jaywin.gitbook.io/leetcode/solutions/0311-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.
