luoheng
10/14/2019 - 7:52 AM

## numMagicSquaresInside

``````
func check(grid [][]int, x, y int) int {
hash := [16]int{}
hash[grid[x-1][y-1]]++
hash[grid[x-1][y]]++
hash[grid[x-1][y+1]]++
hash[grid[x][y-1]]++
hash[grid[x][y]]++
hash[grid[x][y+1]]++
hash[grid[x+1][y-1]]++
hash[grid[x+1][y]]++
hash[grid[x+1][y+1]]++
for i := 1; i < 10; i++ {
if hash[i] != 1 {
return 0
}
}
if grid[x-1][y-1]+grid[x-1][y]+grid[x-1][y+1] != 15 {
return 0
}
if grid[x-1][y-1]+grid[x][y-1]+grid[x+1][y-1] != 15 {
return 0
}
if grid[x-1][y-1]+grid[x][y]+grid[x+1][y+1] != 15 {
return 0
}
if grid[x][y-1]+grid[x][y]+grid[x][y+1] != 15 {
return 0
}
if grid[x+1][y-1]+grid[x+1][y]+grid[x+1][y+1] != 15 {
return 0
}
if grid[x+1][y-1]+grid[x][y]+grid[x-1][y+1] != 15 {
return 0
}
if grid[x-1][y+1]+grid[x][y+1]+grid[x+1][y+1] != 15 {
return 0
}
return 1
}

func numMagicSquaresInside(grid [][]int) int {
sum := 0
for i := 1; i < len(grid)-1; i++ {
for j := 1; j < len(grid[0])-1; j++ {
if grid[i][j] == 5 {
sum += check(grid, i, j)
}
}
}
return sum
}``````