3212. Count Submatrices With Equal Frequency of X and Y

3212. Count Submatrices With Equal Frequency of X and Y

Description

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:

1
2
3
Input: grid = [["X","Y","."],["Y",".","."]]

Output: 3

Explanation:

Example 2:

1
2
3
Input: grid = [["X","X"],["X","Y"]]

Output: 0

Explanation:

No submatrix has an equal frequency of 'X' and 'Y'.

Example 3:

1
2
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 '.'.

Hints/Notes

  • preSum
  • Weekly Contest 405

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int numberOfSubmatrices(vector<vector<char>>& grid) {
int m = grid.size(), n = grid[0].size(), res = 0;
vector<vector<int>> preSum(m + 1, vector<int>(n + 1, 0));
vector<vector<int>> count(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int val = 0;
if (grid[i][j] == 'X') {
val = 1;
} else if (grid[i][j] == 'Y') {
val = -1;
}
preSum[i + 1][j + 1] =
preSum[i][j + 1] + preSum[i + 1][j] - preSum[i][j] + val;
count[i + 1][j + 1] =
count[i][j + 1] + count[i + 1][j] - count[i][j] + abs(val);
if (preSum[i + 1][j + 1] == 0 && count[i + 1][j + 1] > 0) {
res++;
}
}
}
return res;
}
};