Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Express Delivery by blabaster
from heapq import heappop, heappush
def checkio(field_map):
height, width = len(field_map), len(field_map[0])
def neighbours(col, row):
if row:
yield col, row - 1, 'U'
if row < height - 1:
yield col, row + 1, 'D'
if col:
yield col - 1, row, 'L'
if col < width - 1:
yield col + 1, row, 'R'
for y, s in enumerate(field_map):
x = s.find('S')
if x >= 0:
queue = [(0, x, y, True, None, None)] #time, x, y, cargo, letter, prev
visited = [set(), set()]
while True:
time, x, y, cargo, letter, prev = cur = heappop(queue)
if cargo and field_map[y][x] == 'E':
res = []
while prev:
res.append(letter)
time, x, y, cargo, letter, prev = prev
return ''.join(reversed(res))
visited[cargo].add((x, y))
if field_map[y][x] == 'B' and (x, y) not in visited[not cargo]:
heappush(queue, (time + 1, x, y, not cargo, 'B', cur))
for x1, y1, letter in neighbours(x, y):
if (x1, y1) not in visited[cargo] and field_map[y1][x1] in '.BES':
heappush(queue, (time + cargo + 1, x1, y1, cargo, letter, cur))
May 13, 2014