Python數字迷宮是一款有趣的Python游戲,通過編寫Python代碼來尋找路徑解決迷宮難題。以下是一個Python數字迷宮示例代碼:
maze = [ [0, 0, 0, 1, 0], [1, 1, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0] ] # 確定起點和終點 start = (0, 0) end = (4, 4) # 深度優先搜索算法查找路徑 def solve_maze(maze, start, end): stack = [start] visited = set() while stack: curr_pos = stack.pop() if curr_pos == end: return True row, col = curr_pos if not (0<= row< len(maze) and 0<= col< len(maze[0])): continue if curr_pos in visited or maze[row][col] == 1: continue visited.add(curr_pos) for move in [(0, 1), (0, -1), (1, 0), (-1, 0)]: next_pos = (row + move[0], col + move[1]) stack.append(next_pos) return False # 檢查是否存在路徑 if solve_maze(maze, start, end): print("有解!") else: print("無解!")
以上代碼采用深度優先搜索算法實現,從起點開始向周圍四個方向搜索,直到找到終點或者所有路徑都已訪問。如果能找到一條路徑,則返回"有解!",否則返回"無解!"。