-
Notifications
You must be signed in to change notification settings - Fork 17
/
campus-bikes-ii.py
44 lines (32 loc) · 1.18 KB
/
campus-bikes-ii.py
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
33
34
35
36
37
38
39
40
41
42
43
44
import heapq
from typing import List, Set
class Solution:
def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> int:
def distance(
worker_pos: int, bike_pos: int
) -> int:
worker_row, worker_col = workers[worker_pos]
bike_row, bike_col = bikes[bike_pos]
return abs(worker_row - bike_row) + abs(worker_col - bike_col)
heap = [[0, 0, 0]]
seen = set()
while heap:
dist, worker_pos, bikes_bitmap = heapq.heappop(heap)
if worker_pos == len(workers):
return dist
if (worker_pos, bikes_bitmap) in seen:
continue
seen.add((worker_pos, bikes_bitmap))
for bike_pos in range(len(bikes)):
if (1 << bike_pos) & bikes_bitmap:
continue
new_bikes = bikes_bitmap | (1 << bike_pos)
heapq.heappush(
heap,
[
dist + distance(worker_pos, bike_pos),
worker_pos + 1,
new_bikes,
],
)
return 0