LeetCode algorithm_C++ - multiplication of sparse matrices

Given two sparse matrices: a sparse matrix mat1 of size mxk and a sparse matrix mat2 of size kxn, return the result of mat1 x mat2. You can assume that multiplication is always possible.

Example 1:
Insert image description here
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]]

    vector<vector<int>> multiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2) {
    
    
        int m = mat1.size();
        int k = mat1[0].size();
        int n = mat2[0].size();
        unordered_map<int, list<pair<int, int>>> map1;
        unordered_map<int, list<pair<int, int>>> map2;
        
        for (int i {
    
    0}; i < m; i++) {
    
    
            for (int j {
    
    0}; j < k; j++) {
    
    
                if (mat1[i][j] != 0) map1[mat1[i][j]].push_back(make_pair(i, j));
            }
        }        
        
        for (int i = 0; i < k; i++) {
    
    
            for (int j = 0; j < n; j++) {
    
    
                if (mat2[i][j] != 0) map2[mat2[i][j]].push_back(make_pair(i, j));
            }
        }

        vector<vector<int>> res(m, vector<int>(n, 0));
        if (m == 0 || n == 0) return res;

        for (auto& element1 : map1) {
    
    
            for (auto& list_node1 : element1.second) {
    
    
                for (auto& element2 : map2) {
    
    
                    for (auto& list_node2 : element2.second) {
    
    
                        if (list_node1.second == list_node2.first) {
    
    
                            res[list_node1.first][list_node2.second] += element1.first * element2.first;
                        }
                    }
                }
            }
            
        }

        return res;
    }

Guess you like

Origin blog.csdn.net/weixin_43945471/article/details/132724542