1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
| from collections import deque
maze_lines = [ "1111111111111111", "1#01000100000011", "1101110101101011", "1100010001001011", "1111011101100011", "1100000100001111", "1111101101100111", "1100000000100011", "11000000001010@1", "1111111111111111" ]
maze = [] for line in maze_lines: maze.append(line.replace('#', '0').replace('@', '0'))
print("迷宫地图(0=通路,1=墙):") for i, row in enumerate(maze): print(f"Row {i}: {' '.join(list(row))}")
start = (1, 1) end = (8, 14) exact_steps = 24
dirs = { 'w': (-1, 0), 's': (1, 0), 'a': (0, -1), 'd': (0, 1) }
def check_move(row, col, move): """模拟原程序的边界检查,返回新的位置和是否有效""" new_row, new_col = row, col if move == 'w': new_row -= 1 if new_row < 0 or new_row > 9: return None, False elif move == 's': new_row += 1 if new_row == 10: return None, False elif move == 'a': if col == 0: return None, False new_col -= 1 elif move == 'd': new_col += 1 if new_col == 16: return None, False return (new_row, new_col), True
def is_wall(pos): if pos is None: return True row, col = pos index = 17 * row + col actual_index = row * 16 + col if actual_index < 0 or actual_index >= len("".join(maze)): return True return "".join(maze)[actual_index] == '1'
def find_paths_bfs(): queue = deque() queue.append((start[0], start[1], 0, "")) solutions = [] visited_states = set() while queue: row, col, steps, path = queue.popleft() if steps == exact_steps: if (row, col) == end: solutions.append(path) continue for move in ['w', 's', 'a', 'd']: new_pos, valid = check_move(row, col, move) if not valid: continue if is_wall(new_pos): continue new_row, new_col = new_pos new_steps = steps + 1 new_path = path + move state_key = (new_row, new_col, new_steps, new_path[-4:] if len(new_path) >= 4 else new_path) if state_key not in visited_states: visited_states.add(state_key) queue.append((new_row, new_col, new_steps, new_path)) return solutions
def find_paths_dfs(): solutions = [] def dfs(row, col, steps, path): nonlocal solutions if steps == exact_steps: if (row, col) == end: solutions.append(path) return remaining_steps = exact_steps - steps distance = abs(row - end[0]) + abs(col - end[1]) if distance > remaining_steps: return for move in ['w', 's', 'a', 'd']: new_pos, valid = check_move(row, col, move) if not valid: continue if is_wall(new_pos): continue new_row, new_col = new_pos dfs(new_row, new_col, steps + 1, path + move) dfs(start[0], start[1], 0, "") return solutions
print(f"\n起点: {start}") print(f"终点: {end}") print(f"需要步数: {exact_steps}")
def shortest_path_length(): queue = deque() queue.append((start[0], start[1], 0)) visited = [[False] * 16 for _ in range(10)] visited[start[0]][start[1]] = True while queue: row, col, steps = queue.popleft() if (row, col) == end: return steps for move in ['w', 's', 'a', 'd']: new_pos, valid = check_move(row, col, move) if not valid: continue new_row, new_col = new_pos if not is_wall(new_pos) and not visited[new_row][new_col]: visited[new_row][new_col] = True queue.append((new_row, new_col, steps + 1)) return -1
shortest = shortest_path_length() print(f"最短路径长度: {shortest}")
if shortest > exact_steps: print("错误:最短路径长度已经超过24步,不可能有24步的路径") elif shortest == -1: print("错误:无法到达终点") else: print(f"需要绕路增加 {exact_steps - shortest} 步")
print("\n搜索24步路径中...") solutions = find_paths_dfs()
if solutions: print(f"找到 {len(solutions)} 条24步路径") for i, path in enumerate(solutions[:3]): print(f"\n路径 {i+1}: {path}") row, col = start valid = True for j, move in enumerate(path): new_pos, move_valid = check_move(row, col, move) if not move_valid: print(f" 第{j+1}步{move}: 无效移动") valid = False break if is_wall(new_pos): print(f" 第{j+1}步{move}: 撞墙") valid = False break row, col = new_pos print(f" 第{j+1}步{move}: 位置({row},{col})") if valid and (row, col) == end: print(f" ✓ 有效路径,到达终点") else: print(f" ✗ 无效路径") else: print("未找到24步路径,尝试BFS搜索...") solutions = find_paths_bfs() if solutions: print(f"找到 {len(solutions)} 条24步路径") for i, path in enumerate(solutions[:3]): print(f"路径 {i+1}: {path}") else: print("仍未找到24步路径") print("\n寻找接近24步的路径...") for target in range(20, 30): if target == exact_steps: continue exact_steps = target solutions = find_paths_dfs() if solutions: print(f"找到{target}步路径: {solutions[0]}") break
if solutions: print("\n=== 路径可视化 ===") path = solutions[0] row, col = start maze_viz = [list(row) for row in maze_lines] maze_viz[start[0]][start[1]] = 'S' maze_viz[end[0]][end[1]] = 'E' path_positions = [start] for move in path: new_pos, _ = check_move(row, col, move) row, col = new_pos path_positions.append((row, col)) for r, c in path_positions[1:-1]: if maze_viz[r][c] == '0': maze_viz[r][c] = '*' print("迷宫图例: S=起点, E=终点, *=路径, 1=墙, 0=通路") for i, row in enumerate(maze_viz): print(f"Row {i}: {' '.join(row)}")
|