-
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
package com.fishercoder.solutions.fourththousand;
import java.util.HashMap;
import java.util.Map;
public class _3242 {
public static class Solution1 {
class neighborSum {
int[][] matrix;
int m;
int n;
Map<Integer, int[]> map;
public neighborSum(int[][] grid) {
this.matrix = grid;
this.m = grid.length;
this.n = grid[0].length;
this.map = new HashMap<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
map.put(grid[i][j], new int[] {i, j});
}
}
}
public int adjacentSum(int value) {
int[] dirs = new int[] {0, 1, 0, -1, 0};
int[] pos = this.map.get(value);
int sum = 0;
for (int i = 0; i < dirs.length - 1; i++) {
int nextx = pos[0] + dirs[i];
int nexty = pos[1] + dirs[i + 1];
if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n) {
sum += matrix[nextx][nexty];
}
}
return sum;
}
public int diagonalSum(int value) {
int[][] dirs =
new int[][] {
{-1, 1},
{1, 1},
{1, -1},
{-1, -1}
};
int[] pos = this.map.get(value);
int sum = 0;
for (int[] dir : dirs) {
int nextx = pos[0] + dir[0];
int nexty = pos[1] + dir[1];
if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n) {
sum += matrix[nextx][nexty];
}
}
return sum;
}
}
}
}