Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c335184

Browse files
author
Openset
committed
Add: Magic Squares In Grid
1 parent ba05c26 commit c335184

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,29 @@
11
package magic_squares_in_grid
2+
3+
func numMagicSquaresInside(grid [][]int) int {
4+
ans, r, c := 0, len(grid)-1, len(grid[0])-1
5+
for i := 1; i < r; i++ {
6+
flag:
7+
for j := 1; j < c; j++ {
8+
if grid[i][j] == 5 &&
9+
grid[i-1][j-1]+grid[i-1][j]+grid[i-1][j+1] == 15 &&
10+
grid[i+1][j-1]+grid[i+1][j]+grid[i+1][j+1] == 15 &&
11+
grid[i-1][j-1]+grid[i][j-1]+grid[i+1][j-1] == 15 &&
12+
grid[i-1][j+1]+grid[i][j+1]+grid[i+1][j+1] == 15 &&
13+
grid[i-1][j]+grid[i+1][j] == 10 &&
14+
grid[i][j-1]+grid[i][j+1] == 10 &&
15+
grid[i-1][j-1]+grid[i+1][j+1] == 10 &&
16+
grid[i-1][j+1]+grid[i+1][j-1] == 10 {
17+
for m := i - 1; m <= i+1; m++ {
18+
for n := j - 1; n <= j+1; n++ {
19+
if (m != i && n != j && grid[m][n] == 5) || grid[m][n] < 1 || grid[m][n] > 9 {
20+
continue flag
21+
}
22+
}
23+
}
24+
ans++
25+
}
26+
}
27+
}
28+
return ans
29+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,43 @@
11
package magic_squares_in_grid
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input [][]int
7+
expected int
8+
}
9+
10+
func TestNumMagicSquaresInside(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: [][]int{
14+
{4, 3, 8, 4},
15+
{9, 5, 1, 9},
16+
{2, 7, 6, 2},
17+
},
18+
expected: 1,
19+
},
20+
{
21+
input: [][]int{
22+
{5, 5, 5},
23+
{5, 5, 5},
24+
{5, 5, 5},
25+
},
26+
expected: 0,
27+
},
28+
{
29+
input: [][]int{
30+
{1, 8, 6},
31+
{10, 5, 0},
32+
{4, 2, 9},
33+
},
34+
expected: 0,
35+
},
36+
}
37+
for _, tc := range tests {
38+
output := numMagicSquaresInside(tc.input)
39+
if output != tc.expected {
40+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
41+
}
42+
}
43+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /