This website contains ALL LeetCode **Premium** problems for
**FREE!!**.

All leaked interview problems are collected from Internet.

All leaked interview problems are collected from Internet.

A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = `|p2.x - p1.x| + |p2.y - p1.y|`

.

For example, given three people living at `(0,0)`

, `(0,4)`

, and `(2,2)`

:

1 - 0 - 0 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0

The point `(0,2)`

is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6.

b'

\n## Solution

\n

\n#### Approach #1 (Breadth-first Search) [Time Limit Exceeded]

\n\n

\n#### Approach #2 (Manhattan Distance Formula) [Time Limit Exceeded]

\n\n

\n#### Approach #3 (Sorting) [Accepted]

\n\n\n\n\n\n

\n#### Approach #4 (Collect Coordinates in Sorted Order) [Accepted]

\n\n\n

'
\n\n

\n\n

A brute force approach is to evaluate all possible meeting points in the grid. We could apply breadth-first search originating from each of the point.

\nWhile inserting a point into the queue, we need to record the distance of that point from the meeting point. Also, we need an extra `visited`

table to record which point had already been visited to avoid being inserted into the queue again.

public int minTotalDistance(int[][] grid) {\n int minDistance = Integer.MAX_VALUE;\n for (int row = 0; row < grid.length; row++) {\n for (int col = 0; col < grid[0].length; col++) {\n int distance = search(grid, row, col);\n minDistance = Math.min(distance, minDistance);\n }\n }\n return minDistance;\n}\n\nprivate int search(int[][] grid, int row, int col) {\n Queue<Point> q = new LinkedList<>();\n int m = grid.length;\n int n = grid[0].length;\n boolean[][] visited = new boolean[m][n];\n q.add(new Point(row, col, 0));\n int totalDistance = 0;\n while (!q.isEmpty()) {\n Point point = q.poll();\n int r = point.row;\n int c = point.col;\n int d = point.distance;\n if (r < 0 || c < 0 || r >= m || c >= n || visited[r][c]) {\n continue;\n }\n if (grid[r][c] == 1) {\n totalDistance += d;\n }\n visited[r][c] = true;\n q.add(new Point(r + 1, c, d + 1));\n q.add(new Point(r - 1, c, d + 1));\n q.add(new Point(r, c + 1, d + 1));\n q.add(new Point(r, c - 1, d + 1));\n }\n return totalDistance;\n}\n\npublic class Point {\n int row;\n int col;\n int distance;\n public Point(int row, int col, int distance) {\n this.row = row;\n this.col = col;\n this.distance = distance;\n }\n}\n

**Complexity analysis**

- \n
- \n
Time complexity : .\nFor each point in the size grid, the breadth-first search takes at most steps to reach all points. Therefore the time complexity is .

\n \n - \n
Space complexity : .\nThe

\n`visited`

table consists of elements map to each point in the grid. We insert at most points into the queue. \n

\n

You may notice that breadth-first search is unnecessary. You can just calculate the Manhattan distance using the formula:

\n\n\n

\npublic int minTotalDistance(int[][] grid) {\n List<Point> points = getAllPoints(grid);\n int minDistance = Integer.MAX_VALUE;\n for (int row = 0; row < grid.length; row++) {\n for (int col = 0; col < grid[0].length; col++) {\n int distance = calculateDistance(points, row, col);\n minDistance = Math.min(distance, minDistance);\n }\n }\n return minDistance;\n}\n\nprivate int calculateDistance(List<Point> points, int row, int col) {\n int distance = 0;\n for (Point point : points) {\n distance += Math.abs(point.row - row) + Math.abs(point.col - col);\n }\n return distance;\n}\n\nprivate List<Point> getAllPoints(int[][] grid) {\n List<Point> points = new ArrayList<>();\n for (int row = 0; row < grid.length; row++) {\n for (int col = 0; col < grid[0].length; col++) {\n if (grid[row][col] == 1) {\n points.add(new Point(row, col));\n }\n }\n }\n return points;\n}\n\npublic class Point {\n int row;\n int col;\n public Point(int row, int col) {\n this.row = row;\n this.col = col;\n }\n}\n

**Complexity analysis**

- \n
- \n
Time complexity : .\nAssume that is the total number of houses. For each point in the size grid, we calculate the manhattan distance in . Therefore the time complexity is . But do note that there could be up to houses, making the worst case time complexity to be .

\n \n - \n
Space complexity : .

\n \n

\n

Finding the best meeting point in a 2D grid seems difficult. Let us take a step back and solve the 1D case which is much simpler. Notice that the Manhattan distance is the sum of two independent variables. Therefore, once we solve the 1D case, we can solve the 2D case as two independent 1D problems.

\nLet us look at some 1D examples below:

\nCase #1: 1-0-0-0-1\n\nCase #2: 0-1-0-1-0\n

We know the best meeting point must locate somewhere between the left-most and right-most point. For the above two cases, we would select the center point at as the best meeting point. How about choosing the mean of all points as the meeting point?

\nConsider this case:

\nCase #3: 1-0-0-0-0-0-0-1-1\n

Using the mean gives us as the meeting point. The total distance is .

\nBut the best meeting point should be at and the total distance is .

\nYou may argue that the mean is *close* to the optimal point. But imagine a larger case with many 1\'s congregating on the right side and just a single 1 on the left-most side. Using the mean as the meeting point would be far from optimal.

Besides mean, what is a better way to represent the distribution of points? Would median be a better representation? Indeed. In fact, the median *must* be the optimal meeting point.

Case #4: 1-1-0-0-1\n

To see why this is so, let us look at case #4 above and choose the median as our initial meeting point. Assume that the total distance traveled is *d*. Note that we have equal number of points distributed to its left and to its right. Now let us move one step to its right where and notice how the distance changes accordingly.

Since there are two points to the left of , we add to *d*. And *d* is offset by \xe2\x80\x931 since there is one point to the right. This means the distance had overall increased by 1.

Therefore, it is clear that:

\n\n\nAs long as there is equal number of points to the left and right of the meeting point, the total distance is minimized.

\n

Case #5: 1-1-0-0-1-1\n

One may think that the optimal meeting point must fall on one of the 1\'s. This is true for cases with odd number of 1\'s, but not necessarily true when there are even number of 1\'s, just like case #5 does. You can choose any of the to points and the total distance is minimized. Why?

\nThe implementation is direct. First we collect both the row and column coordinates, sort them and select their middle elements. Then we calculate the total distance as the sum of two independent 1D problems.

\npublic int minTotalDistance(int[][] grid) {\n List<Integer> rows = new ArrayList<>();\n List<Integer> cols = new ArrayList<>();\n for (int row = 0; row < grid.length; row++) {\n for (int col = 0; col < grid[0].length; col++) {\n if (grid[row][col] == 1) {\n rows.add(row);\n cols.add(col);\n }\n }\n }\n int row = rows.get(rows.size() / 2);\n Collections.sort(cols);\n int col = cols.get(cols.size() / 2);\n return minDistance1D(rows, row) + minDistance1D(cols, col);\n}\n\nprivate int minDistance1D(List<Integer> points, int origin) {\n int distance = 0;\n for (int point : points) {\n distance += Math.abs(point - origin);\n }\n return distance;\n}\n

Note that in the code above we do not need to sort *rows*, why?

**Complexity analysis**

- \n
- \n
Time complexity : .\nSince there could be at most points, therefore the time complexity is due to sorting.

\n \n - \n
Space complexity : .

\n \n

\n

We could use the Selection algorithm to select the median in time, but there is an easier way. Notice that we can collect both the row and column coordinates in sorted order.

\npublic int minTotalDistance(int[][] grid) {\n List<Integer> rows = collectRows(grid);\n List<Integer> cols = collectCols(grid);\n int row = rows.get(rows.size() / 2);\n int col = cols.get(cols.size() / 2);\n return minDistance1D(rows, row) + minDistance1D(cols, col);\n}\n\nprivate int minDistance1D(List<Integer> points, int origin) {\n int distance = 0;\n for (int point : points) {\n distance += Math.abs(point - origin);\n }\n return distance;\n}\n\nprivate List<Integer> collectRows(int[][] grid) {\n List<Integer> rows = new ArrayList<>();\n for (int row = 0; row < grid.length; row++) {\n for (int col = 0; col < grid[0].length; col++) {\n if (grid[row][col] == 1) {\n rows.add(row);\n }\n }\n }\n return rows;\n}\n\nprivate List<Integer> collectCols(int[][] grid) {\n List<Integer> cols = new ArrayList<>();\n for (int col = 0; col < grid[0].length; col++) {\n for (int row = 0; row < grid.length; row++) {\n if (grid[row][col] == 1) {\n cols.add(col);\n }\n }\n }\n return cols;\n}\n

\nYou can calculate the distance without knowing the median using a two pointer approach. This neat approach is inspired by @larrywang2014\'s solution.

public int minTotalDistance(int[][] grid) {\n List<Integer> rows = collectRows(grid);\n List<Integer> cols = collectCols(grid);\n return minDistance1D(rows) + minDistance1D(cols);\n}\n\nprivate int minDistance1D(List<Integer> points) {\n int distance = 0;\n int i = 0;\n int j = points.size() - 1;\n while (i < j) {\n distance += points.get(j) - points.get(i);\n i++;\n j--;\n }\n return distance;\n}\n

**Complexity analysis**

- \n
- \n
Time complexity : .

\n \n - \n
Space complexity : .

\n \n