python使用堆棧stack走出迷宮


stack一般用來存儲已有的狀態,對於解決迷宮問題最是合適.

迷宮問題沒有什么好的解決辦法,只能采用蠻力窮舉的辦法,要點是已經走過的路徑(包括可行路線和不可行路線)要進行標記,這樣可以避免原地死循環

# 用list實現一個stack
class Stack(object):
    def __init__(self):
        self.item = list()

    # 入棧
    def push(self, node):
        self.item.append(node)

    # 刪除並返回棧頂一個元素
    def pop(self):
        return self.item.pop()

    # 返回棧頂一個元素
    def peek(self):
        return self.item[-1]

    def __str__(self):
        return str(self.item)


class Maze(object):
    MAZE_WALL = "*"
    PATH_TOKEN = "x"
    TRIED_TOKEN = "o"

    def __init__(self):
        self.maze_cells = [['*', '*', '*', '*', '*'],
                           ['*', None, '*', None, '*'],
                           ['*', None, None, None, '*'],
                           ['*', None, '*', None, None],
                           ['*', None, '*', '*', '*']]
        self.start = (4, 1)
        self.end = (3, 4)
        self.numRows, self.numCols = (5, 5)
        self.path = None

    # 搜索可行路線
    def find_path(self):
        self.path = Stack()
        # 起始點肯定是必經之路,入棧,標記為路徑
        row, col = self.start
        self._mark_path(row, col)
        while not self._exit_found(row, col):
            # 左1=col-1
            if self._valid_move(row, col - 1):
                self._mark_path(row, col - 1)
                col = col - 1
            # 上1=row-1
            elif self._valid_move(row - 1, col):
                self._mark_path(row - 1, col)
                row = row - 1
            # 右1=col+1
            elif self._valid_move(row, col + 1):
                self._mark_path(row, col + 1)
                col = col + 1
            # 下1=row+1
            elif self._valid_move(row + 1, col):
                self._mark_path(row + 1, col)
                row = row + 1
            else:
                self._mark_tried(row, col)
                row, col = self.path.peek()
        return self.path

    # 判斷是否是可行進路線
    def _valid_move(self, row, col):
        return 0 <= row < self.numRows and 0 <= col < self.numCols and self.maze_cells[row][col] is None

    # 判斷是否找到出口
    def _exit_found(self, row, col):
        return (row, col) == self.end

    # 標記為已嘗試但不可行path
    def _mark_tried(self, row, col):
        self.maze_cells[row][col] = self.TRIED_TOKEN
        self.path.pop()

    # 標記為可行路線
    def _mark_path(self, row, col):
        self.maze_cells[row][col] = self.PATH_TOKEN
        self.path.push((row, col))


if __name__ == '__main__':
    m = Maze()
    path = m.find_path()
    print(path)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM