Medium
Given a 2D character matrix grid
, where grid[i][j]
is either 'X'
, 'Y'
, or '.'
, return the number of submatrices that contains:
grid[0][0]
'X'
and 'Y'
.'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 '.'
.class Solution {
fun numberOfSubmatrices(grid: Array<CharArray>): Int {
val n = grid[0].size
var ans = 0
val row = Array(n) { IntArray(2) }
for (chars in grid) {
val count = IntArray(2)
for (j in 0 until n) {
if (chars[j] != '.') {
count[chars[j].code - 'X'.code]++
}
row[j][0] += count[0]
row[j][1] += count[1]
if (row[j][0] > 0 && row[j][0] == row[j][1]) {
ans++
}
}
}
return ans
}
}