Untitled
unknown
python
a year ago
2.9 kB
11
Indexable
from collections import deque
class CastleBlock():
def __init__(self, is_walkable = True, is_escape = False):
self.can_walk = is_walkable
self.can_escape = is_escape
def is_walkable(self):
return self.can_walk
def is_escape(self):
return self.can_escape
class Wall(CastleBlock):
def __init__(self):
super().__init__(False, False)
class EscapePoint(CastleBlock):
def __init__(self):
super().__init__(True, True)
class Castle():
def __init__(self, rows, cols, walls, escape_point):
self.map = [[CastleBlock() for row in range(rows)] for col in range(cols)]
# initialize walls
for wall in walls:
row, col = wall
self.map[row][col] = Wall()
# initialize escape point
escape_row, escape_col = escape_point
self.map[escape_row][escape_col] = EscapePoint()
def in_castle(self, row, col):
return row >= 0 and row < len(self.map) and col >= 0 and col < len(self.map[0])
def is_walkable(self, row, col):
return self.in_castle(row, col) and self.map[row][col].is_walkable()
def is_escape(self, row, col):
return self.in_castle(row, col) and self.map[row][col].is_escape()
class Adventurer():
def __init__(self, start_row, start_col, steps = 0):
self.x_pos = start_row
self.y_pos = start_col
self.steps = steps
def get_position(self):
return (self.x_pos, self.y_pos)
def get_steps(self):
return self.steps
def move(self, dx, dy):
self.x_pos += dx
self.y_pos += dy
self.steps += 1
def escape_castle(rows, columns, walls, escape_point):
castle = Castle(rows, columns, walls, escape_point)
adventurers = deque([Adventurer(0, 0)])
directions = [[0,1],[0,-1],[1,0],[-1,0]]
while adventurers:
curr_adventurer = adventurers.pop()
x, y = curr_adventurer.get_position()
for dx, dy in directions:
walkable_directions = 0
next_x, next_y = x + dx, y + dy
if castle.is_walkable(next_x, next_y):
# if escape point, escape and return route steps
if castle.is_escape(next_x, next_y):
return curr_adventurer.get_steps() + 1
# if first adventurer, make move
if walkable_directions == 0:
curr_adventurer.move(dx, dy)
walkable_directions += 1
adventurers.append(curr_adventurer)
else:
new_adventurer = Adventurer(next_x, next_y, curr_adventurer.get_steps()+1)
adventurers.append(new_adventurer)
return -1
rows = 2
cols = 2
walls = [[0, 1]]
escape_point = [1, 1]
print(escape_castle(rows, cols, walls, escape_point))Editor is loading...
Leave a Comment