311. 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 |

 

Constraints:

  • 1 <= A.length, B.length <= 100
  • 1 <= A[i].length, B[i].length <= 100
  • -100 <= A[i][j], B[i][j] <= 100

Rust Solution

struct Solution;

impl Solution {
    fn multiply(a: Vec<Vec<i32>>, b: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
        let l = a.len();
        let m = b.len();
        let n = b[0].len();
        let mut res = vec![vec![0; n]; l];
        for i in 0..l {
            for j in 0..n {
                for k in 0..m {
                    res[i][j] += a[i][k] * b[k][j];
                }
            }
        }
        res
    }
}

#[test]
fn test() {
    let a = vec_vec_i32![[1, 0, 0], [-1, 0, 3]];
    let b = vec_vec_i32![[7, 0, 0], [0, 0, 0], [0, 0, 1]];
    let res = vec_vec_i32![[7, 0, 0], [-7, 0, 3]];
    assert_eq!(Solution::multiply(a, b), res);
}

Having problems with this solution? Click here to submit an issue on github.