|
| 1 | +package array; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by gouthamvidyapradhan on 10/03/2019 |
| 5 | + * A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of |
| 6 | + * values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan |
| 7 | + * Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. |
| 8 | + * <p> |
| 9 | + * Example: |
| 10 | + * <p> |
| 11 | + * Input: |
| 12 | + * <p> |
| 13 | + * 1 - 0 - 0 - 0 - 1 |
| 14 | + * | | | | | |
| 15 | + * 0 - 0 - 0 - 0 - 0 |
| 16 | + * | | | | | |
| 17 | + * 0 - 0 - 1 - 0 - 0 |
| 18 | + * <p> |
| 19 | + * Output: 6 |
| 20 | + * <p> |
| 21 | + * Explanation: Given three people living at (0,0), (0,4), and (2,2): |
| 22 | + * The point (0,2) is an ideal meeting point, as the total travel distance |
| 23 | + * of 2+2+2=6 is minimal. So return 6. |
| 24 | + * <p> |
| 25 | + * Solution: O(N ^ 2 + M ^ 2) + O(N x M): Calculate the total number of persons in each row and each column and then |
| 26 | + * take a minimum of cartesian product of each row and each column. |
| 27 | + */ |
| 28 | +public class BestMeetingPoint { |
| 29 | + |
| 30 | + /** |
| 31 | + * Main method |
| 32 | + * |
| 33 | + * @param args |
| 34 | + */ |
| 35 | + public static void main(String[] args) { |
| 36 | + int[][] grid = {{1, 0, 0, 0, 1}, {0, 0, 0, 0, 0}, {0, 0, 1, 0, 0}}; |
| 37 | + System.out.println(new BestMeetingPoint().minTotalDistance(grid)); |
| 38 | + } |
| 39 | + |
| 40 | + public int minTotalDistance(int[][] grid) { |
| 41 | + int[] countR = new int[grid.length]; |
| 42 | + int[] countC = new int[grid[0].length]; |
| 43 | + |
| 44 | + int[] distR = new int[grid.length]; |
| 45 | + int[] distC = new int[grid[0].length]; |
| 46 | + |
| 47 | + for (int i = 0; i < grid.length; i++) { |
| 48 | + for (int j = 0; j < grid[0].length; j++) { |
| 49 | + if (grid[i][j] == 1) { |
| 50 | + countR[i]++; |
| 51 | + countC[j]++; |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + for (int i = 0; i < distR.length; i++) { |
| 57 | + for (int j = 0; j < distR.length; j++) { |
| 58 | + if (countR[j] != 0) { |
| 59 | + distR[i] += Math.abs(j - i) * countR[j]; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + for (int i = 0; i < distC.length; i++) { |
| 65 | + for (int j = 0; j < distC.length; j++) { |
| 66 | + if (countC[j] != 0) { |
| 67 | + distC[i] += Math.abs(j - i) * countC[j]; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + int min = Integer.MAX_VALUE; |
| 73 | + for (int i = 0; i < distR.length; i++) { |
| 74 | + for (int j = 0; j < distC.length; j++) { |
| 75 | + min = Math.min(min, distR[i] + distC[j]); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + return min; |
| 80 | + } |
| 81 | +} |
0 commit comments