|
| 1 | +package com.fishercoder.solutions.fourththousand; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +public class _3242 { |
| 7 | + public static class Solution1 { |
| 8 | + class neighborSum { |
| 9 | + int[][] matrix; |
| 10 | + int m; |
| 11 | + int n; |
| 12 | + Map<Integer, int[]> map; |
| 13 | + |
| 14 | + public neighborSum(int[][] grid) { |
| 15 | + this.matrix = grid; |
| 16 | + this.m = grid.length; |
| 17 | + this.n = grid[0].length; |
| 18 | + this.map = new HashMap<>(); |
| 19 | + for (int i = 0; i < m; i++) { |
| 20 | + for (int j = 0; j < n; j++) { |
| 21 | + map.put(grid[i][j], new int[]{i, j}); |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + public int adjacentSum(int value) { |
| 27 | + int[] dirs = new int[]{0, 1, 0, -1, 0}; |
| 28 | + int[] pos = this.map.get(value); |
| 29 | + int sum = 0; |
| 30 | + for (int i = 0; i < dirs.length - 1; i++) { |
| 31 | + int nextx = pos[0] + dirs[i]; |
| 32 | + int nexty = pos[1] + dirs[i + 1]; |
| 33 | + if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n) { |
| 34 | + sum += matrix[nextx][nexty]; |
| 35 | + } |
| 36 | + } |
| 37 | + return sum; |
| 38 | + } |
| 39 | + |
| 40 | + public int diagonalSum(int value) { |
| 41 | + int[][] dirs = new int[][]{ |
| 42 | + {-1, 1}, |
| 43 | + {1, 1}, |
| 44 | + {1, -1}, |
| 45 | + {-1, -1} |
| 46 | + }; |
| 47 | + int[] pos = this.map.get(value); |
| 48 | + int sum = 0; |
| 49 | + for (int[] dir : dirs) { |
| 50 | + int nextx = pos[0] + dir[0]; |
| 51 | + int nexty = pos[1] + dir[1]; |
| 52 | + if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n) { |
| 53 | + sum += matrix[nextx][nexty]; |
| 54 | + } |
| 55 | + } |
| 56 | + return sum; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments