Given a 2D character matrix grid, where grid[i][j] is either 'X', 'Y', or '.', return the number of submatrices that contain:
grid[0][0]
an equal frequency of 'X' and 'Y'.
at least one 'X'.
Example 1:
Input:grid = [["X","Y","."],["Y",".","."]]
Output:3
Explanation:
Example 2:
Input:grid = [["X","X"],["X","Y"]]
Output:0
Explanation:
No submatrix has an equal frequency of 'X' and 'Y'.
Example 3:
Input:grid = [[".","."],[".","."]]
Output:0
Explanation:
No submatrix has at least one 'X'.
Constraints:
1 <= grid.length, grid[i].length <= 1000
grid[i][j] is either 'X', 'Y', or '.'.
Solutions
Solution 1: 2D Prefix Sum
According to the problem description, we only need to calculate the prefix sums $s[i][j][0]$ and $s[i][j][1]$ for each position $(i, j)$, which represent the number of characters X and Y in the submatrix from $(0, 0)$ to $(i, j)$, respectively. If $s[i][j][0] > 0$ and $s[i][j][0] = s[i][j][1]$, it means the condition is met, and we increment the answer by one.
After traversing all positions, return the answer.
The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ represent the number of rows and columns of the matrix, respectively.