Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Dark Labyrinth by cerankas
from math import inf
DIRECTIONS = {-1:'W', 1:'E', -1j:'N', 1j:'S'}
map = {}
position = 0
def distance_to_wall(p:complex, dir:complex) -> int:
while p + dir in map and map[p + dir] != 'X':
dir += dir / abs(dir)
return int(abs(dir)) - 1 if p + dir in map else inf
def is_unexplored(p:complex) -> bool:
return any(distance_to_wall(p, dir) == inf for dir in DIRECTIONS)
def is_exit(p:complex) -> bool:
return map[p] == 'E'
def path_to_fulfill_condition(condition:callable) -> (str, complex):
queue = [('', position)]
passed = set()
while queue:
path0, p0 = queue.pop(0)
passed.add(p0)
for dir in DIRECTIONS:
p = p0 + dir
if p in passed or p not in map or map[p] == 'X': continue
path = path0 + DIRECTIONS[dir]
if condition(p):
return path, p
queue.append((path, p))
def find_path(visible: list[str]) -> str:
global map, position
for y, row in enumerate(visible):
if 'P' in row:
offset = -(row.index('P') + 1j * y)
break
for y, row in enumerate(visible):
for x, char in enumerate(row):
p = position + offset + x + 1j * y
if p not in map:
if char in '.XE':
map[p] = char
if 'E' in map.values():
path, _ = path_to_fulfill_condition(is_exit)
map = {}
position = 0
return path
path, position = path_to_fulfill_condition(is_unexplored)
return path
Oct. 16, 2023
Comments: