lc-go/solutions/8/q840/solution.go
2026-01-04 14:44:06 +09:00

63 lines
1 KiB
Go

package q840
func checkSquare(x, y int, grid [][]int) bool {
seen := uint16(0)
rowSum, colSum := [3]int{}, [3]int{}
diag1sum, diag2sum := 0, 0
for ty := range 3 {
for tx := range 3 {
num := grid[y+ty][x+tx]
if num < 1 || num > 9 {
return false
}
tSeen := seen | (1 << (num - 1))
if tSeen == seen { // duplicate number
return false
}
seen = tSeen
rowSum[ty] += num
colSum[tx] += num
if tx == ty {
diag1sum += num
}
if tx+ty == 2 {
diag2sum += num
}
}
}
if diag1sum != diag2sum {
return false
}
for i := range 3 {
if rowSum[i] != diag1sum || colSum[i] != diag1sum {
return false
}
}
return true
}
func numMagicSquaresInside(grid [][]int) int {
if len(grid) < 3 || len(grid[0]) < 3 {
return 0
}
w, h := len(grid[0]), len(grid)
count := 0
for y := range h - 2 {
for x := range w - 2 {
if grid[y+1][x+1] != 5 { // the center cell has to be 5
continue
}
if checkSquare(x, y, grid) {
count++
}
}
}
return count
}
var _ = numMagicSquaresInside