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:

        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 |
// not the correct solution, but I am skipping this problem for now.

  vector<int> multiply(vector<vector<int>> *A, vector<vector<int>> *B)
  {
      vector<int> result;
      int sum = 0;
      // mulitply every row
      for (int i = 0; i < A[0].size(); ++i) {
          // with every column
          for (int j = 0; j < (*B).size(); ++j) {
              sum += (*A)[i][j] * (*B)[j][i];
          }
          result.push_back(sum);
          sum = 0;
      }


      return result;
  }


  int main()
  {
      vector<vector<int>> arrayA = {    { 1, 0, 0 }, 
                                      { -1, 0, 3 } 
                                   };


      vector<vector<int>> arrayB = { 
                                      { 7, 0, 0 },
                                      { 0, 0, 0 }, 
                                      { 0, 0, 1 } 
                                   };
  }

Last updated