variable to store the number of submatrices with all 0 s
int to_sum = 0 ; while ( i >= 0 ) { int c = 0 ; while ( q . size ( ) != 0 and q . top ( ) . first > p_arr [ i ] [ j ] ) { to_sum -= ( q . top ( ) . second + 1 ) * ( q . top ( ) . first - p_arr [ i ] [ j ] ) ; c += q . top ( ) . second + 1 ; q . pop ( ) ; } to_sum += p_arr [ i ] [ j ] ; count_zero_submatrices += to_sum ; q . push ( { p_arr [ i ] [ j ] , c } ) ; i -- ; } } return ( n * ( n + 1 ) * n * ( n + 1 ) ) / 4 - count_zero_submatrices ; }