Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions problems/magic-squares-in-grid/magic_squares_in_grid.go
Original file line number Diff line number Diff line change
@@ -1 +1,29 @@
package magic_squares_in_grid

func numMagicSquaresInside(grid [][]int) int {
ans, r, c := 0, len(grid)-1, len(grid[0])-1
for i := 1; i < r; i++ {
flag:
for j := 1; j < c; j++ {
if grid[i][j] == 5 &&
grid[i-1][j-1]+grid[i-1][j]+grid[i-1][j+1] == 15 &&
grid[i+1][j-1]+grid[i+1][j]+grid[i+1][j+1] == 15 &&
grid[i-1][j-1]+grid[i][j-1]+grid[i+1][j-1] == 15 &&
grid[i-1][j+1]+grid[i][j+1]+grid[i+1][j+1] == 15 &&
grid[i-1][j]+grid[i+1][j] == 10 &&
grid[i][j-1]+grid[i][j+1] == 10 &&
grid[i-1][j-1]+grid[i+1][j+1] == 10 &&
grid[i-1][j+1]+grid[i+1][j-1] == 10 {
for m := i - 1; m <= i+1; m++ {
for n := j - 1; n <= j+1; n++ {
if (m != i && n != j && grid[m][n] == 5) || grid[m][n] < 1 || grid[m][n] > 9 {
continue flag
}
}
}
ans++
}
}
}
return ans
}
42 changes: 42 additions & 0 deletions problems/magic-squares-in-grid/magic_squares_in_grid_test.go
Original file line number Diff line number Diff line change
@@ -1 +1,43 @@
package magic_squares_in_grid

import "testing"

type caseType struct {
input [][]int
expected int
}

func TestNumMagicSquaresInside(t *testing.T) {
tests := [...]caseType{
{
input: [][]int{
{4, 3, 8, 4},
{9, 5, 1, 9},
{2, 7, 6, 2},
},
expected: 1,
},
{
input: [][]int{
{5, 5, 5},
{5, 5, 5},
{5, 5, 5},
},
expected: 0,
},
{
input: [][]int{
{1, 8, 6},
{10, 5, 0},
{4, 2, 9},
},
expected: 0,
},
}
for _, tc := range tests {
output := numMagicSquaresInside(tc.input)
if output != tc.expected {
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
}
}
}