迷宫回溯问题
# 迷宫回溯问题
"""
* 约定迷宫的出口是row,column 即右下角的那个点
* 约定数字1为墙,2为走过的路,3为死路,0表示没有走过
"""
class Maze(object):
def __init__(self, x, y):
self.x = x
self.y = y
# 初始化迷宫
self.maze = [[0 for i in range(y)] for _ in range(x)]
# 初始化墙
for i in range(x):
self.maze[i][0] = 1
self.maze[i][y - 1] = 1
for i in range(y):
self.maze[0][i] = 1
self.maze[x - 1][i] = 1
def set_block(self, x, y):
self.maze[x][y] = 1
def print(self):
for item in self.maze:
print(item)
def pass_maze(self, x, y):
"""
起点位置 x y 坐标 走过的路线使用2标记
移动策略默认采用 ↓ → ↑ ←
:return:
"""
if self.maze[self.x - 2][self.y - 2] == 2:
return True
else:
# 没走过标记为走过
if self.maze[x][y] == 0:
self.maze[x][y] = 2
if self.pass_maze(x + 1, y):
# 尝试一直往下走
# return True
pass
elif self.pass_maze(x, y + 1):
# 尝试一直往右走
# return True
pass
elif self.pass_maze(x - 1, y):
# 尝试一直往上走
# return True
pass
elif self.pass_maze(x, y - 1):
# 尝试一直往左走
# return True
pass
else:
return False
return False
if __name__ == '__main__':
maze = Maze(7, 8)
maze.set_block(3, 1)
maze.set_block(3, 2)
maze.print()
print('=' * 30)
maze.pass_maze(1, 1)
maze.print()
八皇后问题
"""
八皇后问题
用一个一维数组表示八皇后问题的一种解法 数组的index 为第index排的皇后 值为皇后在这排摆放的位置
"""
class Queen(object):
def __init__(self, x):
self.max = x
self.chess = [0 for _ in range(self.max)]
self.count = 0
def check(self, x):
for i in range(x):
# 检查之前的摆放是否正确
# 判断是否在同一列 和 同一斜线
if self.chess[i] == self.chess[x] or (abs(x - i) == abs(self.chess[i] - self.chess[x])):
return False
return True
def play(self, x):
if x == self.max:
# 摆放到最后一个了
print(self.chess)
self.count += 1
return
for i in range(self.max):
self.chess[x] = i
if self.check(x):
# todo 贪心优化
self.play(x + 1)
if __name__ == '__main__':
queen = Queen(8)
queen.play(0)
print(queen.count)