|
| 1 | +import itertools |
| 2 | + |
| 3 | +from typing import List, Tuple |
| 4 | +from collections import deque |
| 5 | + |
| 6 | +def solution(maps: List[str]) -> int: |
| 7 | + n, m = len(maps), len(maps[0]) |
| 8 | + start = [ |
| 9 | + (x, y) |
| 10 | + for x, y in itertools.product(range(m), range(n)) |
| 11 | + if maps[y][x] == 'S' |
| 12 | + ][0] |
| 13 | + |
| 14 | + lever, lever_step = find_path(maps, start, "L") |
| 15 | + if lever_step == -1: |
| 16 | + return -1 |
| 17 | + |
| 18 | + end_step = find_path(maps, lever, "E")[1] |
| 19 | + if end_step == -1: |
| 20 | + return -1 |
| 21 | + |
| 22 | + return lever_step + end_step |
| 23 | + |
| 24 | + |
| 25 | +def find_path(maps: List[str], start: Tuple[int, int], target: str) -> Tuple[Tuple[int, int], int]: |
| 26 | + n, m = len(maps), len(maps[0]) |
| 27 | + queue, visited = deque([(0, start)]), set() |
| 28 | + |
| 29 | + while queue: |
| 30 | + step, (x, y) = queue.popleft() |
| 31 | + if (x, y) in visited: |
| 32 | + continue |
| 33 | + |
| 34 | + visited.add((x, y)) |
| 35 | + for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]: |
| 36 | + nx, ny = x + dx, y + dy |
| 37 | + if not (0 <= nx < m and 0 <= ny < n): |
| 38 | + continue |
| 39 | + |
| 40 | + if maps[ny][nx] == target: |
| 41 | + return (nx, ny), step + 1 |
| 42 | + |
| 43 | + if maps[ny][nx] != 'X': |
| 44 | + queue.append((step + 1, (nx, ny))) |
| 45 | + |
| 46 | + return (-1, -1), -1 |
0 commit comments