
Input: mat =[[1,0,1],[1,1,0],[1,1,0]]Output: 13Explanation:
There are 6 rectangles of side 1x1.There are 2 rectangles of side 1x2.There are 3 rectangles of side 2x1.There is1 rectangle of side 2x2.There is1 rectangle of side 3x1.Total number of rectangles =6+2+3+1+1=13.

Input: mat =[[0,1,1,0],[0,1,1,1],[1,1,1,0]]Output: 24Explanation:
There are 8 rectangles of side 1x1.There are 5 rectangles of side 1x2.There are 2 rectangles of side 1x3.There are 4 rectangles of side 2x1.There are 2 rectangles of side 2x2.There are 2 rectangles of side 3x1.There is1 rectangle of side 3x2.Total number of rectangles =8+5+2+4+2+2+1=24.
We can treat each row as the base of a histogram, where the height at each column is the number of consecutive ones above (including the current row). For each row, we use a monotonic stack to efficiently count the number of submatrices ending at that row.
classSolution {
funnumSubmat(mat: Array<IntArray>): Int {
val m = mat.size; val n = mat[0].size
val h = IntArray(n)
var ans = 0for (i in0 until m) {
for (j in0 until n) h[j] = if (mat[i][j] ==1) h[j] + 1else0val stack = mutableListOf<Int>()
val sum = IntArray(n)
for (j in0 until n) {
while (stack.isNotEmpty() && h[stack.last()] >= h[j]) stack.removeAt(stack.size-1)
if (stack.isNotEmpty()) {
val prev = stack.last()
sum[j] = sum[prev] + h[j] * (j - prev)
} else {
sum[j] = h[j] * (j + 1)
}
ans += sum[j]
stack.add(j)
}
}
return ans
}
}
classSolution:
defnumSubmat(self, mat: list[list[int]]) -> int:
m, n = len(mat), len(mat[0])
h = [0] * n
ans =0for i in range(m):
for j in range(n):
h[j] = h[j] +1if mat[i][j] else0 stack, sum_ = [], [0] * n
for j in range(n):
while stack and h[stack[-1]] >= h[j]:
stack.pop()
if stack:
prev = stack[-1]
sum_[j] = sum_[prev] + h[j] * (j - prev)
else:
sum_[j] = h[j] * (j +1)
ans += sum_[j]
stack.append(j)
return ans