> For the complete documentation index, see [llms.txt](https://jaywin.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jaywin.gitbook.io/leetcode/solutions/0311-sparse-matrix-multiplication.md).

# 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
*/
```
