-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution3242.go
80 lines (72 loc) · 1.6 KB
/
solution3242.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package solution3242
// ============================================================================
// 3242. Design Neighbor Sum Service
// URL: https://leetcode.com/problems/design-neighbor-sum-service/
// ============================================================================
/*
goos: linux
goarch: amd64
pkg: GoLeetCode/solutions/3242---Design-Neighbor-Sum-Service
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
BenchmarkGetFinalState
BenchmarkGetFinalState-24 86156235 13.78 ns/op 0 B/op 0 allocs/op
PASS
*/
type NeighborSum struct {
grid [][]int
n int
}
func Constructor(grid [][]int) NeighborSum {
return NeighborSum{
grid: grid,
n: len(grid),
}
}
func (this *NeighborSum) AdjacentSum(value int) int {
sum := 0
loop:
for y := 0; y < this.n; y++ {
for x := 0; x < this.n; x++ {
if this.grid[y][x] == value {
if y-1 >= 0 {
sum += this.grid[y-1][x]
}
if x-1 >= 0 {
sum += this.grid[y][x-1]
}
if y+1 < this.n {
sum += this.grid[y+1][x]
}
if x+1 < this.n {
sum += this.grid[y][x+1]
}
break loop
}
}
}
return sum
}
func (this *NeighborSum) DiagonalSum(value int) int {
sum := 0
loop:
for y := 0; y < this.n; y++ {
for x := 0; x < this.n; x++ {
if this.grid[y][x] == value {
if x-1 >= 0 && y-1 >= 0 {
sum += this.grid[y-1][x-1]
}
if x+1 < this.n && y-1 >= 0 {
sum += this.grid[y-1][x+1]
}
if x-1 >= 0 && y+1 < this.n {
sum += this.grid[y+1][x-1]
}
if x+1 < this.n && y+1 < this.n {
sum += this.grid[y+1][x+1]
}
break loop
}
}
}
return sum
}