Precomputing the number of 1 s
ones = [ [ 0 for i in range ( C + 1 ) ] for i in range ( R + 1 ) ] NEW_LINE for i in range ( 1 , R + 1 , 1 ) : NEW_LINE INDENT for j in range ( 1 , C + 1 , 1 ) : NEW_LINE INDENT ones [ i ] [ j ] = ( ones [ i - 1 ] [ j ] + ones [ i ] [ j - 1 ] - ones [ i - 1 ] [ j - 1 ] + ( mat [ i - 1 ] [ j - 1 ] == 1 ) ) NEW_LINE DEDENT DEDENT