老鼠走迷宫(python语言)

老鼠走迷宫—————————————-

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()

猜你喜欢

转载自blog.csdn.net/zhangyu4863/article/details/80904977