Solution 1: Only do the calculation for non-zero elements in A
classSolution(object):defmultiply(self,A,B):""" :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ rowA =len(A) colA =len(A[0]) colB =len(B[0]) ret = [[0for column inrange(colB)] for row inrange(rowA)]for i inrange(rowA):for j inrange(colA):if A[i][j] !=0:for k inrange(colB): ret[i][k] += A[i][j] * B[j][k]return ret
Solution 2. Using dictionary to store non-zero elements in A
classSolution(object):defmultiply(self,A,B):""" :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ m =len(A) l =len(A[0]) n =len(B[0]) ret = [[0for col inrange(n)] for row inrange(m)] dic ={}# final all nonzero elements in Afor i inrange(m): tmp ={}for j inrange(l):if A[i][j] !=0: tmp[j]= A[i][j] dic[i]= tmp# compute matrix multiplicationfor i inrange(m): tmp = dic.get(i)for j, val in tmp.items():for k inrange(n): ret[i][k] += val * B[j][k]return ret