Created
March 25, 2013 14:21
-
-
Save aisk/5237449 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from pprint import pprint | |
RIGHT, DOWN, LEFT, UP = 1, 2, 3, 4 | |
class MatrixWalker(object): | |
def __init__(self, width): | |
self.width = width | |
x = width + 2 # 多一圈,作为最外圈的墙壁 | |
self.matrix = [] | |
for i in xrange(x): | |
line = [] | |
for j in xrange(x): | |
line.append(None) | |
self.matrix.append(line) | |
self.matrix[0] = [0] * x | |
self.matrix[-1] = [0] * x | |
for line in self.matrix: | |
line[0] = 0 | |
line[-1] = 0 | |
self.x = 1 # 初始位置 | |
self.y = 1 | |
self.dire = RIGHT # 初始方向 | |
self.count = 1 # 走过的步数 | |
def show(self): | |
pprint(self.matrix) | |
def turn_direction(self): | |
'''撞到墙壁时转换方向,固定→↓←↑的顺序 | |
''' | |
self.dire = self.dire+1 if self.dire<4 else 1 | |
def peek_next(self): | |
'''查看下一步位置的状态 | |
''' | |
return { | |
RIGHT: self.matrix[self.y][self.x+1], | |
DOWN: self.matrix[self.y+1][self.x], | |
LEFT: self.matrix[self.y][self.x-1], | |
UP: self.matrix[self.y-1][self.x], | |
}[self.dire] | |
def go_next(self): | |
'''走到下一步 | |
''' | |
self.count += 1 | |
if self.dire == RIGHT: | |
self.x += 1 | |
elif self.dire == DOWN: | |
self.y += 1 | |
elif self.dire == LEFT: | |
self.x -= 1 | |
elif self.dire == UP: | |
self.y -= 1 | |
def walk(self): | |
'''递归遍历矩阵,太宽时有可能会达到最深函数调用层数 | |
''' | |
if self.count > self.width * self.width: | |
return | |
self.matrix[self.y][self.x] = self.count | |
if self.peek_next() is not None: | |
self.turn_direction() | |
self.go_next() | |
return self.walk() | |
if __name__ == '__main__': | |
m = MatrixWalker(5) | |
m.walk() | |
m.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment