Skip to content

Commit

Permalink
Leetcode/1066 campuis bikes
Browse files Browse the repository at this point in the history
  • Loading branch information
herrera-ignacio committed Jan 7, 2024
1 parent c5fe1a8 commit db9873a
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@
- [976: Largest perimeter triangle](problems/leetcode/976)
- [977: Squares of a sorted array](problems/leetcode/977)
- [1047: Remove all adjacent duplicates in a string](problems/leetcode/1047) - Stack
- [1066: Campus bikes II](problems/leetcode/1066) - Matrix - Medium
- [1089: Duplicate Zeros](problems/leetcode/1089) - Queue
- [1198: Find smallest common element in all rows](problems/leetcode/1198) - Matrix
- [1208: Unique number of occurrences](problems/leetcode/1208) - Set + Map
Expand Down
57 changes: 57 additions & 0 deletions problems/leetcode/1066/top-down-dp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
*
* @param {number[][]} workers
* @param {number[][]} bikes
*/
function assignBikes(workers, bikes) {
const memo = {};
return dfsMinDistanceSum(workers, bikes, 0, 0, memo);
}

/**
*
* @param {number[]} worker
* @param {number[]} bike
*/
function findManhattanDistance(worker, bike) {
const res = Math.abs(worker[0] - bike[0]) + Math.abs(worker[1] - bike[1]);
console.log(res);
return res;
}

function dfsMinDistanceSum(workers, bikes, workerIdx, bikeMask, memo) {
// Finished assigning bikes to workers
if (workerIdx >= workers.length) return 0;

// Already calculated
if (memo[bikeMask] !== undefined) return memo[bikeMask];

let minDistanceSum = Infinity;

for (let bikeIdx = 0; bikeIdx < bikes.length; bikeIdx++) {
// console.log(bikeMask);
// Check if the bike is available
if ((bikeMask & (1 << bikeIdx)) === 0) {
// Add the current distance
// and repeat the process for next worker
// Also, mark the bike as assigned in the mask
const newBikeMask = bikeMask | (1 << bikeIdx);
minDistanceSum = Math.min(
minDistanceSum,
findManhattanDistance(workers[workerIdx], bikes[bikeIdx])
+ dfsMinDistanceSum(
workers,
bikes,
workerIdx + 1,
newBikeMask,
memo
)
);
}
}

// Memoize the result corresponding to mask
memo[bikeMask] = minDistanceSum;

return minDistanceSum;
}

0 comments on commit db9873a

Please sign in to comment.