8000 :sparkles: Added solution to 840 · ninefive/awesome-golang-leetcode@78fa867 · GitHub
[go: up one dir, main page]

Skip to content

Commit 78fa867

Browse files
author
Sathish Babu
committed
✨ Added solution to 840
1 parent 1d7d584 commit 78fa867

File tree

3 files changed

+69
-9
lines changed

3 files changed

+69
-9
lines changed

src/0840.Magic-Squares-In-Grid/README.md

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,29 @@
55
66
## Description
77

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+
812
**Example 1:**
913

1014
```
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.
1331
```
1432

1533
## 题意
Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,36 @@
11
package Solution
22

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]
536
}

src/0840.Magic-Squares-In-Grid/Solution_test.go

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,23 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs [][]int
14+
expect int
1515
}{
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},
1930
}
2031

2132
// 开始测试

0 commit comments

Comments
 (0)
0