classSolution(object): defgetMinimumTime(self, time, fruits, limit): """ :type time: List[int] :type fruits: List[List[int]] :type limit: int :rtype: int """ res = 0 for i inrange(len(fruits)): if fruits[i][1] % limit != 0: res += ((fruits[i][1]//limit) + 1) * time[fruits[i][0]] else: res += (fruits[i][1]//limit) * time[fruits[i][0]] return res
whilelen(pq) != 0: tmp = heapq.heappop(pq) x, y = tmp[1] for i inrange(4): nx = x + dx[i] ny = y + dy[i] if nx >= 0and nx < len(matrix) and ny >= 0and ny < len(matrix[0]): # 这里不用设置visited数组是关键 if (matrix[x][y] == '^'and i == 2) or (matrix[x][y] == 'v'and i == 0) or (matrix[x][y] == '<'and i == 3) or (matrix[x][y] == '>'and i == 1): if dp[x][y] < dp[nx][ny]: # 只有更小的才入队,貌似不是优先队列也行 dp[nx][ny] = dp[x][y] heapq.heappush(pq, (tmp[0], [nx, ny])) else: if dp[x][y] + 1 < dp[nx][ny]: # 只有更小的才入队,貌似不是优先队列也行 dp[nx][ny] = dp[x][y] + 1 heapq.heappush(pq, (tmp[0]+1, [nx, ny]))
whilelen(queue) != 0: x, y = queue[0] queue = queue[1:] for i inrange(4): nx = x + dx[i] ny = y + dy[i] if nx >= 0and nx < len(matrix) and ny >= 0and ny < len(matrix[0]): # 这里不用设置visited数组是关键 if (matrix[x][y] == '^'and i == 2) or (matrix[x][y] == 'v'and i == 0) or (matrix[x][y] == '<'and i == 3) or (matrix[x][y] == '>'and i == 1): if dp[x][y] < dp[nx][ny]: # 只有更小的才入队,貌似不是优先队列也行 dp[nx][ny] = dp[x][y] queue.append([nx, ny]) else: if dp[x][y] + 1 < dp[nx][ny]: # 只有更小的才入队,貌似不是优先队列也行 dp[nx][ny] = dp[x][y] + 1 queue.append([nx, ny])
record = [[[-1, 0] for _ inrange(len(matrix[0]))] for _ inrange(len(matrix))] visited = [[0for _ inrange(len(matrix[0]))] for _ inrange(len(matrix))] total_vis = 0 target_vis = len(matrix[0]) * len(matrix)
# 第一次从start开始走,把所有能走到的位置都标记上,如果走到了end则跳出并且输出0 # x纵向,y横向 sx, sy = start nx, ny = sx, sy
while visited[nx][ny] == 0and nx >= 0and nx < len(matrix) and ny >= 0and ny < len(matrix[0]): # 如果走到了end则跳出,并且输出0 if nx == end[0] and ny == end[1]: return0
# 暴力走 now_status = 0 jilu_i = 0 jilu_j = 0 while total_vis != target_vis: # 找到一个与now_status相邻的位置 break_flag = False for i inrange(jilu_i, len(matrix)): for j inrange(jilu_j, len(matrix[0])): can_flag = False if visited[i][j] == 0: # 如果还没有访问过 # 如果临近的可达状态有上一个now_status的 for k inrange(4): nnx = i + dx[k] nny = j + dy[k] if nnx >= 0and nnx < len(matrix) and nny >= 0and nny < len(matrix[0]) and record[nnx][nny][0] == now_status: # can_flag = True break
if can_flag: break_flag = True break if break_flag: break
if break_flag: # 还能找到
jilu_i = i jilu_j = j
nx, ny = i, j while nx >= 0and nx < len(matrix) and ny >= 0and ny < len(matrix[0]) and visited[nx][ny] == 0: # 修改状态 record[nx][ny][0] = now_status + 1 record[nx][ny][1] = 1
# 增加 visited[i][j] = 1 total_vis += 1
# 按照当前的格子走 if matrix[nx][ny] == '>': ny = ny + 1 elif matrix[nx][ny] == '<': ny = ny - 1 elif matrix[nx][ny] == '^': nx = nx - 1 elif matrix[nx][ny] == 'v': nx = nx + 1