Skip to content

Instantly share code, notes, and snippets.

@jjangga0214
Created March 27, 2018 08:57
Show Gist options
  • Save jjangga0214/5a43839b6923f3cb624ed1c0518aaabb to your computer and use it in GitHub Desktop.
Save jjangga0214/5a43839b6923f3cb624ed1c0518aaabb to your computer and use it in GitHub Desktop.
import functools
import copy
class Maze:
'''
2차원 리스트를 wrapping 한다.
'''
def __init__(self, maze, *, end, start=(0, 0), function=copy.deepcopy):
self.maze = function(maze)
self.end = end
self.start = start
def get(self, row, col):
return self.maze[row][col]
def put(self, row, col, val):
self.maze[row][col] = val
class MazeResolver:
_MARK_VAL = 2
routings = (
lambda row, col: (row - 1, col + 0),
lambda row, col: (row - 1, col + 1),
lambda row, col: (row + 0, col + 1),
lambda row, col: (row + 1, col + 1),
lambda row, col: (row + 1, col + 0),
lambda row, col: (row + 1, col - 1),
lambda row, col: (row + 0, col - 1),
lambda row, col: (row - 1, col - 1),
)
def __init__(self, maze):
self.maze = copy.deepcopy(maze)
self.cursor = self.maze.start
#
self.route = [self.maze.start, ]
def look_around(self):
for routing in MazeResolver.routings:
edge = routing(*self.cursor)
try:
if not self.maze.get(*edge): # 0인 경우
return edge
except IndexError:
continue
return False # 주위에 0이 없을 경우
def track(self, edge, consumer=print):
self.maze.put(*edge, MazeResolver._MARK_VAL)
self.cursor = edge
self.route.append(self.cursor) # 현재 위치(edge)까지 기록한다.
if consumer:
consumer(*self.cursor)
def proceed(self):
while self.cursor != self.maze.end:
edge = self.look_around()
if edge:
self.track(edge)
else:
try:
self.route.pop()
self.track(self.route.pop())
except IndexError: # start 로 다시 돌아온 경우, self.route 가 empty 된다.
return False
return True
if __name__ == '__main__':
raw_mz = ([0, 1, 1, 1, 1, 1],
[1, 0, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 1],
[1, 1, 0, 1, 1, 1],
[1, 0, 1, 0, 0, 1],
[1, 1, 1, 1, 1, 0])
mz = Maze(raw_mz, start=(0, 0), end=(5, 5), )
mr = MazeResolver(mz)
result = mr.proceed()
print("result =", result)
print("path =", mr.route)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment