- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_3242.java
61 lines (56 loc) · 1.96 KB
/
_3242.java
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
packagecom.fishercoder.solutions.fourththousand;
importjava.util.HashMap;
importjava.util.Map;
publicclass_3242 {
publicstaticclassSolution1 {
classneighborSum {
int[][] matrix;
intm;
intn;
Map<Integer, int[]> map;
publicneighborSum(int[][] grid) {
this.matrix = grid;
this.m = grid.length;
this.n = grid[0].length;
this.map = newHashMap<>();
for (inti = 0; i < m; i++) {
for (intj = 0; j < n; j++) {
map.put(grid[i][j], newint[] {i, j});
}
}
}
publicintadjacentSum(intvalue) {
int[] dirs = newint[] {0, 1, 0, -1, 0};
int[] pos = this.map.get(value);
intsum = 0;
for (inti = 0; i < dirs.length - 1; i++) {
intnextx = pos[0] + dirs[i];
intnexty = pos[1] + dirs[i + 1];
if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n) {
sum += matrix[nextx][nexty];
}
}
returnsum;
}
publicintdiagonalSum(intvalue) {
int[][] dirs =
newint[][] {
{-1, 1},
{1, 1},
{1, -1},
{-1, -1}
};
int[] pos = this.map.get(value);
intsum = 0;
for (int[] dir : dirs) {
intnextx = pos[0] + dir[0];
intnexty = pos[1] + dir[1];
if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n) {
sum += matrix[nextx][nexty];
}
}
returnsum;
}
}
}
}