File tree Expand file tree Collapse file tree 3 files changed +69
-9
lines changed
src/0840.Magic-Squares-In-Grid Expand file tree Collapse file tree 3 files changed +69
-9
lines changed Original file line number Diff line number Diff line change 5
5
6
6
## Description
7
7
8
+ A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
9
+
10
+ Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
11
+
8
12
** Example 1:**
9
13
10
14
```
11
- Input: a = "11", b = "1"
12
- Output: "100"
15
+ Input: [[4,3,8,4],
16
+ [9,5,1,9],
17
+ [2,7,6,2]]
18
+ Output: 1
19
+ Explanation:
20
+ The following subgrid is a 3 x 3 magic square:
21
+ 438
22
+ 951
23
+ 276
24
+
25
+ while this one is not:
26
+ 384
27
+ 519
28
+ 762
29
+
30
+ In total, there is only one magic square inside the given grid.
13
31
```
14
32
15
33
## 题意
Original file line number Diff line number Diff line change 1
1
package Solution
2
2
3
- func Solution (x bool ) bool {
4
- return x
3
+ func Solution (grid [][]int ) int {
4
+ var ret int
5
+ for i := 0 ; i < len (grid )- 2 ; i ++ {
6
+ for j := 0 ; j < len (grid [i ])- 2 ; j ++ {
7
+ if isValid (grid , i , j ) {
8
+ ret ++
9
+ }
10
+ }
11
+ }
12
+ return ret
13
+ }
14
+
15
+ func isValid (grid [][]int , row , col int ) bool {
16
+ if grid [row + 1 ][col + 1 ] != 5 {
17
+ return false
18
+ }
19
+ data := make ([]int , 16 )
20
+ for i := row ; i <= row + 2 ; i ++ {
21
+ for j := col ; j <= col + 2 ; j ++ {
22
+ data [grid [i ][j ]]++
23
+ }
24
+ }
25
+ for i := 1 ; i <= 9 ; i ++ {
26
+ if data [i ] != 1 {
27
+ return false
28
+ }
29
+ }
30
+ for i := 0 ; i <= 2 ; i ++ {
31
+ if grid [row + i ][col ]+ grid [row + i ][col + 1 ]+ grid [row + i ][col + 2 ] != grid [row ][col + i ]+ grid [row + 1 ][col + i ]+ grid [row + 2 ][col + i ] {
32
+ return false
33
+ }
34
+ }
35
+ return grid [row ][col ]+ grid [row + 1 ][col + 1 ]+ grid [row + 2 ][col + 2 ] == grid [row ][col + 2 ]+ grid [row + 1 ][col + 1 ]+ grid [row + 2 ][col ]
5
36
}
Original file line number Diff line number Diff line change @@ -10,12 +10,23 @@ func TestSolution(t *testing.T) {
10
10
// 测试用例
11
11
cases := []struct {
12
12
name string
13
- inputs bool
14
- expect bool
13
+ inputs [][] int
14
+ expect int
15
15
}{
16
- {"TestCase" , true , true },
17
- {"TestCase" , true , true },
18
- {"TestCase" , false , false },
16
+ {"TestCase" ,
17
+ [][]int {
18
+ {4 , 3 , 8 , 4 },
19
+ {9 , 5 , 1 , 9 },
20
+ {2 , 7 , 6 , 2 },
21
+ },
22
+ 1 },
23
+ {"TestCase" ,
24
+ [][]int {
25
+ {1 , 3 , 8 , 2 },
26
+ {7 , 5 , 1 , 9 },
27
+ {2 , 9 , 6 , 3 },
28
+ },
29
+ 0 },
19
30
}
20
31
21
32
// 开始测试
You can’t perform that action at this time.
0 commit comments