1066. Campus Bikes II
On a campus represented as a 2D grid, there are N
workers and M
bikes, with N <= M
. Each worker and bike is a 2D coordinate on this grid.
We assign one unique bike to each worker so that the sum of the Manhattan distances between each worker and their assigned bike is minimized.
The Manhattan distance between two points p1
and p2
is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|
.
Return the minimum possible sum of Manhattan distances between each worker and their assigned bike.
Example 1:

Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
Output: 6
Explanation:
We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6.
Example 2:

Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
Output: 4
Explanation:
We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4.
Note:
0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000
All worker and bike locations are distinct.
1 <= workers.length <= bikes.length <= 10
// Bottom-Up Dynamic Programming
int dist(const vector<int>& p, const vector<int>& q) {
return abs(p[0] - q[0]) + abs(p[1] - q[1]);
}
int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) { // time: O(n * m * 2^m); space: O(n * 2^m)
int n = workers.size(), m = bikes.size();
vector<vector<int> > dp(n + 1, vector<int>(1 << m, numeric_limits<int>::max() / 2 ) );
dp[0][0] = 0;
int res = numeric_limits<int>::max();
for (int i = 1; i <= n; ++i) {
for (int state = 1; state < (1 << m); ++state) {
for (int j = 0; j < m; ++j) {
if ((state & (1 << j) ) == 0) continue;
int pre_state = state ^ (1 << j);
dp[i][state] = min(dp[i][state], dp[i - 1][pre_state] + dist(workers[i - 1], bikes[j]) );
if (i == n) res = min(res, dp[i][state]);
}
}
}
return res;
}
// Top-Down Dynamic Programming
int helper(int i, int usedBits, vector<vector<int> >& workers, vector<vector<int> >& bikes, vector<vector<int> >& memo) {
if (i == workers.size()) return 0;
if (memo[i][usedBits] != 0) return memo[i][usedBits];
int res = numeric_limits<int>::max();
for (int j = 0; j < bikes.size(); ++j) {
if ((usedBits & (1 << j) ) != 0) continue;
int dist = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]);
res = min(res, dist + helper(i + 1, usedBits | (1 << j), workers, bikes, memo) );
}
return memo[i][usedBits] = res;
}
int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
vector<vector<int> > memo(workers.size(), vector<int>(1 << bikes.size() ) );
return helper(0, 0, workers, bikes, memo);
}
Last updated
Was this helpful?