老鼠走迷宫—————————————-
0为可走,1为不可走
x为行数,y为列数
matrix = []
exit_x = 1
exit_y = 1
class Node:
def __init__(self, x, y):
self.x = x
self.y = y
self.next = None
class TraceRecord:
def __init__(self):
self.first = None
self.last = None
def is_empty(self):
return self.first is None
def insert(self, x, y):
new_node = Node(x, y)
if self.first is None:
self.first = new_node
self.last = new_node
else:
self.last.next = new_node
self.last = new_node
def delete(self):
if self.first is None:
print('队列已为空\n')
return error
new_node = self.first
while new_node.next != self.last:
new_node = new_node.next
new_node.next = self.last.next
self.last = new_node
def check_next(x, y, ex, ey):
if x == ex and y == ey:
if matrix[x-1][y] == 1 or matrix[x+1][y] == 1 or matrix[x][y-1] == 1 or matrix[x][y+1] == 2:
return 1
if matrix[x-1][y] == 1 or matrix[x+1][y] == 1 or matrix[x][y-1] == 2 or matrix[x][y+1] == 1:
return 1
if matrix[x-1][y] == 1 or matrix[x+1][y] == 2 or matrix[x][y-1] == 1 or matrix[x][y+1] == 1:
return 1
if matrix[x-1][y] == 2 or matrix[x+1][y] == 1 or matrix[x][y-1] == 1 or matrix[x][y+1] == 1:
return 1
return 0
def main():
path = TraceRecord()
x = 1
y = 1
print('迷宫的路径(标记为0的部分)')
for i in range(10):
for j in range(12):
print(matrix[i][j], end='')
print()
while x <= exit_x and y <= exit_y:
matrix[x][y] = 2
if matrix[x-1][y] == 0:
x -= 1
path.insert(x, y)
elif matrix[x+1][y] == 0:
x += 1
path.insert(x, y)
elif matrix[x][y-1] == 0:
y += 1
path.insert(x, y)
elif matrix[x][y+1] == 0:
y += 1
path.insert(x, y)
elif check_next(x, y, exit_x, exit_y) == 1:
break
else:
matrix[x][y] = 2
path.delete()
x = path.last.x
y = path.last.y
print('路径为(2表示的地方)\n')
for i in range(10):
for j in range(12):
print(matrix[i][j], end='')
print()