[LeetCode] Campus Bikes II

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.

Return the minimum possible sum of Manhattan distances between each worker and their assigned bike.

The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
vector<vector<int>> distance;
int dp[11][1<<11];

int dfs(int w, int mask) {
if(w == distance.size()) return 0;
if(dp[w][mask] != -1) return dp[w][mask];
dp[w][mask] = INT_MAX;
for(int i = 0; i < distance[w].size(); i++) {
if(mask & (1<<i)) continue;
dp[w][mask] = min(dp[w][mask], dfs(w + 1, mask | (1<<i)) + distance[w][i]);
}

return dp[w][mask];
}
public:
int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
int n = workers.size(), m = bikes.size();
memset(dp,-1,sizeof(dp));

distance = vector<vector<int>>(n, vector<int>(m));

for(int i = 0; i < n; i++) { //init distance
for(int j = 0; j < m; j++) {
distance[i][j] = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]);
}
}


return dfs(0,0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/campus-bikes-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.