Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
branch if box solution in Clear category for Express Delivery by DiZ
from heapq import heappush, heappop
def checkio(field):
dirs = {'D':(1,0), 'U':(-1,0), 'R':(0,1), 'L':(0,-1)}
start = next((i, j) for i, l in enumerate(field) for j, c in enumerate(l) if c == 'S')
seen, bag = set(), [(0, True, start, '')]
while bag:
score, cargo, (x, y), path = heappop(bag)
if cargo and field[x][y] == 'E': return path
seen.add((cargo, (x, y)))
if field[x][y] == 'B':
heappush(bag, [score + 1, not cargo, (x, y), path + 'B'])
for direction, (u, v) in dirs.items():
xn, yn = u + x, v + y
if (cargo, (xn, yn)) in seen: continue
if 0 <= xn < len(field) and 0 <= yn < len(field[0]) and field[xn][yn] != 'W':
heappush(bag, [score + 1 + cargo, cargo, (xn, yn), path + direction])
Feb. 18, 2015
Comments: