52 lines
1 KiB
Go
52 lines
1 KiB
Go
// Package q3212 implements a solution for https://leetcode.com/problems/count-submatrices-with-equal-frequency-of-x-and-y/
|
|
package q3212
|
|
|
|
type State struct {
|
|
x, y, dot uint32
|
|
}
|
|
|
|
func (s *State) Add(another *State) {
|
|
s.x += another.x
|
|
s.y += another.y
|
|
s.dot += another.dot
|
|
}
|
|
|
|
func (s *State) Sub(another *State) {
|
|
s.x -= another.x
|
|
s.y -= another.y
|
|
s.dot -= another.dot
|
|
}
|
|
|
|
func numberOfSubmatrices(grid [][]byte) int {
|
|
cntPrev, cntCur := make([]State, len(grid[0])), make([]State, len(grid[0]))
|
|
|
|
submatrices := 0
|
|
for row := range grid {
|
|
for col := range grid[0] {
|
|
st := State{}
|
|
switch grid[row][col] {
|
|
case 'X':
|
|
st.x = 1
|
|
case 'Y':
|
|
st.y = 1
|
|
case '.':
|
|
st.dot = 1
|
|
}
|
|
|
|
cntCur[col] = st
|
|
cntCur[col].Add(&cntPrev[col])
|
|
if col > 0 {
|
|
cntCur[col].Add(&cntCur[col-1])
|
|
cntCur[col].Sub(&cntPrev[col-1])
|
|
}
|
|
|
|
if cntCur[col].x > 0 && cntCur[col].y == cntCur[col].x {
|
|
submatrices++
|
|
}
|
|
}
|
|
cntPrev, cntCur = cntCur, cntPrev
|
|
}
|
|
return submatrices
|
|
}
|
|
|
|
var _ = numberOfSubmatrices
|