Give simple, common, and optimised Java solution class Solution € public int…
- User
Give simple, common, and optimised Java solution
class Solution € public int minTotalDistance(int [] [] grid) {
- Assistant
Give simple, common, and optimised Java solution
class Solution € public int minTotalDistance(int [] [] grid) {
To solve the problem of finding the minimum total distance in a grid, we can exploit the properties of median positions. The minimum distance in a grid can be efficiently found by locating the median of the occupied points because the median minimizes the sum of absolute deviations.
Here's a simple and optimized Java solution for the problem:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
public int minTotalDistance(int[][] grid) {
// Collect x and y coordinates separately
List<Integer> rows = new ArrayList<>();
List<Integer> cols = new ArrayList<>();
// Traverse the grid and collect x and y indices where there are 1s
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == 1) {
rows.add(r);
cols.add(c);
}
}
}
// The optimal meeting row is the median of rows
int rowMedian = rows.get(rows.size() / 2);
// Sort columns to find the median
Collections.sort(cols);
int colMedian = cols.get(cols.size() / 2);
// Calculate the minimum total distance by summing Manhattan distances to the median
return minDistance1D(rows, rowMedian) + minDistance1D(cols, colMedian);
}
private int minDistance1D(List<Integer> points, int median) {
int distance = 0;
for (int point : points) {
distance += Math.abs(point - median);
}
return distance;
}
}
Collect Indices: The first step is to collect all x and y indices where there are 1s in the grid. We use two separate lists: rows for the row indices and cols for the column indices.
Median Calculation:
rows.cols.cols, we sort them to find the correct median.Manhattan Distance:
This solution efficiently finds the minimum total distance by leveraging the median property, with a time complexity of O(n log n) due to sorting the columns. The approach is optimal for grid-based problems where movement costs are only affected by row and column changes.
Not yet included in a published release.