You are given an m x n0-indexed 2D array of positive integers heights
where heights[i][j] is the height of the person standing at position (i, j).
A person standing at position (row1, col1) can see a person standing at position (row2, col2) if:
The person at (row2, col2) is to the right or below the person at (row1, col1). More formally, this means that either row1 == row2 and col1 < col2orrow1 < row2 and col1 == col2.
Everyone in between them is shorter than both of them.
Return anm x n2D array of integersanswerwhereanswer[i][j]is the number of people that the person at position(i, j)can see.

Input: heights =[[3,1,4,2,5]]Output: [[2,1,2,1,0]]Explanation:
- The person at(0,0) can see the people at(0,1) and (0,2).Note that he cannot see the person at(0,4) because the person at(0,2)is taller than him.- The person at(0,1) can see the person at(0,2).- The person at(0,2) can see the people at(0,3) and (0,4).- The person at(0,3) can see the person at(0,4).- The person at(0,4) cannot see anybody.
Example 2:
1
2
3
4
5
6
7
8
9
10

Input: heights =[[5,1],[3,1],[4,1]]Output: [[3,1],[2,1],[1,0]]Explanation:
- The person at(0,0) can see the people at(0,1),(1,0) and (2,0).- The person at(0,1) can see the person at(1,1).- The person at(1,0) can see the people at(1,1) and (2,0).- The person at(1,1) can see the person at(2,1).- The person at(2,0) can see the person at(2,1).- The person at(2,1) cannot see anybody.
For each person, we need to count how many people they can see to the right and below, following the rule that all people in between must be shorter than both. This is a classic monotonic stack problem, similar to “next greater element” but counting visible people.
classSolution {
funcanSeePersons(heights: Array<IntArray>): Array<IntArray> {
val m = heights.size
val n = heights[0].size
val ans = Array(m) { IntArray(n) }
// Right direction
for (i in0 until m) {
val st = ArrayDeque<Int>()
for (j in n-1 downTo 0) {
var cnt = 0while (st.isNotEmpty() && heights[i][j] > heights[i][st.peek()]) {
st.pop(); cnt++ }
if (st.isNotEmpty()) cnt++ ans[i][j] += cnt
st.push(j)
}
}
// Down direction
for (j in0 until n) {
val st = ArrayDeque<Int>()
for (i in m-1 downTo 0) {
var cnt = 0while (st.isNotEmpty() && heights[i][j] > heights[st.peek()][j]) {
st.pop(); cnt++ }
if (st.isNotEmpty()) cnt++ ans[i][j] += cnt
st.push(i)
}
}
return ans
}
}
classSolution:
defcanSeePersons(self, heights: list[list[int]]) -> list[list[int]]:
m, n = len(heights), len(heights[0])
ans = [[0]*n for _ in range(m)]
# Right directionfor i in range(m):
st = []
for j in range(n-1, -1, -1):
cnt =0while st and heights[i][j] > heights[i][st[-1]]:
st.pop(); cnt +=1if st: cnt +=1 ans[i][j] += cnt
st.append(j)
# Down directionfor j in range(n):
st = []
for i in range(m-1, -1, -1):
cnt =0while st and heights[i][j] > heights[st[-1]][j]:
st.pop(); cnt +=1if st: cnt +=1 ans[i][j] += cnt
st.append(i)
return ans