Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Labyrinth:
- def __init__(self, configuration):
- self.configuration = [x.strip() for x in configuration]
- self.walls = []
- self.entry = None
- self.exits = []
- for y, row in enumerate(self.configuration):
- for x, ch in enumerate(row):
- if ch == '#':
- self.walls.append((x, y))
- elif ch == '@':
- self.entry = (x, y)
- elif ch == '$':
- self.exits.append((x, y))
- self.height = len(self.configuration)
- self.width = len(self.configuration[0])
- self.walls.append(self.entry)
- self.path = []
- self.pathes = []
- def get_directions(self, position, ignore=None):
- if ignore is None:
- ignore = []
- x, y = position
- directions = []
- if x > 0 and (x-1, y) not in self.walls and (x-1, y) not in ignore:
- directions.append((x-1, y))
- if y > 0 and (x, y-1) not in self.walls and (x, y-1) not in ignore:
- directions.append((x, y-1))
- if x < self.width-1 and (x+1, y) not in self.walls and (x+1, y) not in ignore:
- directions.append((x+1, y))
- if y < self.height-1 and (x, y+1) not in self.walls and (x, y+1) not in ignore:
- directions.append((x, y+1))
- return directions
- def has_exit(self, path):
- for exit in self.exits:
- if exit in path:
- return exit
- def move(self, start, ignore=None):
- if ignore is None:
- ignore = []
- if start not in ignore:
- ignore = ignore + [start]
- directions = self.get_directions(start, ignore)
- if directions:
- exit = self.has_exit(directions)
- if exit:
- return [start, exit]
- # print('>>', directions)
- result = []
- # print('|', start, '->', directions)
- for direction in directions:
- path = self.move(direction, ignore)
- # print(':', direction, '->', path)
- if path:
- if len(directions) == 1:
- return [start] + path
- else:
- result.append([start]+path)
- # print('|', result)
- return result or None
- else:
- return [start]
- def decode_path(self, seq, initial=None):
- initial = initial or []
- result = initial[:]
- for x in seq:
- if type(x) is not list:
- result.append(x)
- else:
- self.pathes.append(self.decode_path(x, initial=result))
- return result
- def build_path(self):
- import pprint
- self.path = labyrinth.move(self.entry)
- # pprint.pprint(self.path)
- print('---')
- self.decode_path(self.path)
- def draw_all(self):
- [
- self.draw(x)
- for x in sorted(self.pathes, key=lambda t:len(t))
- if self.has_exit(x)]
- def draw(self, path):
- print('Path length:', len(path))
- for x in range(len(self.configuration[0])):
- print('%1x' % x, end='')
- print()
- for y, row in enumerate(self.configuration):
- for x, ch in enumerate(row):
- print('*' if (x, y) in path else ch, end='')
- print(' %d' % y)
- with open('input.txt', 'r') as f:
- labyrinth = Labyrinth(f.readlines())
- labyrinth.build_path()
- if labyrinth.path:
- labyrinth.draw_all()
- else:
- print('No exit!')
- # print(labyrinth.path)
Add Comment
Please, Sign In to add comment