码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Sparse Matrix Multiplication"

时间:2015-11-30 08:31:15      阅读:389      评论:0      收藏:0      [点我收藏+]

标签:

Taking advantage of ‘sparse‘

class Solution 
{
public:
    vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) 
    {
        vector<vector<int>> ret;
        
        int ha = A.size();
        if(!ha) return ret;
        int wa = A[0].size();
        if(!wa) return ret;
        
        int hb = wa;
        int wb = B[0].size();
        if(!wb) return ret;
        
        // Preprocessing
        unordered_map<int, bool> ArowZero, BcolZero;
        for(int i = 0; i < ha; i ++)
        {
            bool bAllZero = true;
            for(int j = 0; j < wa; j ++)
            {
                if(A[i][j])
                {
                    bAllZero = false;
                    break;
                }
            }
            ArowZero[i] = bAllZero;
        }
        for(int i = 0; i < wb; i ++)
        {
            bool bAllZero = true;
            for(int j = 0; j < hb; j ++)
            {
                if(B[j][i])
                {
                    bAllZero = false;
                    break;
                }
            }
            BcolZero[i] = bAllZero;
        }
        
        ret.assign(ha, vector<int>(wb, 0));
        for(int i = 0; i < ha; i ++)
        for(int j = 0; j < wb; j ++)
        {
            if(!ArowZero[i] && !BcolZero[j])
            {
                int sum = 0;
                for(int k = 0; k < wa; k ++)
                {
                    sum += A[i][k] * B[k][j];
                }
                ret[i][j] = sum;
            }
        }
        return ret;
    }
};

LeetCode "Sparse Matrix Multiplication"

标签:

原文地址:http://www.cnblogs.com/tonix/p/5006202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!