Variable to store the number of submatrices with all 0 s
var to_sum = 0 ; while ( i >= 0 ) { var c = 0 ; while ( q . length != 0 && q [ q . length - 1 ] [ 0 ] > p_arr [ i ] [ j ] ) { to_sum -= ( q [ q . length - 1 ] [ 1 ] + 1 ) * ( q [ q . length - 1 ] [ 0 ] - p_arr [ i ] [ j ] ) ; c += q [ q . length - 1 ] [ 1 ] + 1 ; q . pop ( ) ; } to_sum += p_arr [ i ] [ j ] ; count_zero_submatrices += to_sum ; q . push ( [ p_arr [ i ] [ j ] , c ] ) ; i -- ; } }