Python 解决一个简单的迷宫问题 在线等
发布网友
发布时间:2022-04-18 09:21
我来回答
共3个回答
热心网友
时间:2022-04-18 10:50
具体是什么情况呢
# -*- coding: utf-8 -*-
matrix = []
row, col = 0, 0
def LoadData():
global matrix
file = open("maze.txt")
lines = file.readlines()
for line in lines:
matrix.append(line.strip())
def Init():
r = len(matrix)
c = len(matrix[0])
global row, col
for cc in xrange(c):
for rr in xrange(r):
if matrix[rr][cc] in ('O', 'F'):
row, col = rr, cc
OutputPos()
return
def OutputPos():
print "You are at position (%d, %d)" % (row, col)
def Move(d):
global row, col
m = (0, 0)
if d == 'N':
m = (-1, 0)
elif d == 'E':
m = (0, 1)
elif d == 'S':
m = (1, 0)
elif d == 'W':
m = (0, -1)
if row + m[0] >= 0 and row + m[0] < len(matrix) and col + m[1] >= 0 and col + m[1] < len(matrix[0]) and matrix[row + m[0]][col + m[1]] in ('O', 'F'):
row = row + m[0]
col = col + m[1]
OutputPos()
else:
print "You can't go in that direction"
def Input():
cmd = raw_input("Command: ")
cmd = cmd.strip()
if cmd == '?':
print '''\
? - Help.
N - move North one square.
S - move South one square.
E - move East one square.
W - move West one square.
R - Reset to the beginning.
B - Back up a move.
L - List all possible legal directions from the current position.
Q - Quit.'''
OutputPos()
elif cmd in ('N', 'E', 'S', 'W'):
Move(cmd)
if matrix[row][col] == 'F':
print "Congratulations - you made it"
elif cmd == 'L':
l = []
if row - 1 >= 0 and matrix[row - 1][col] in ('O', 'F'):
l.append('N')
if col + 1 < len(matrix[0]) and matrix[row][col + 1] in ('O', 'F'):
l.append('E')
if row + 1 < len(matrix) and matrix[row + 1][col] in ('O', 'F'):
l.append('S')
if col - 1 >= 0 and matrix[row][col - 1] in ('O', 'F'):
l.append('W')
for i, x in enumerate(l):
if i > 0:
print ",",
print x,
print ""
elif cmd == 'R':
Init()
elif cmd == 'Q':
if raw_input("Are you sure you want to quit? [y] or n:").strip() == 'y':
return False
else:
print "Invalid Command:", cmd
OutputPos()
return True
if __name__ == "__main__":
LoadData()
Init()
while Input():
pass
热心网友
时间:2022-04-18 12:08
问题补充:大概能有一页的样子 谢谢了 =这个是某次应求帮人写的程序#调用上面定于的sparse方法。其实简单的处理用不着这么做的……单纯为了扩展性,cQupyI