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
|
maze=[ [1,1,1,1,1,1,1,1,1,1], [1,0,0,1,0,0,0,1,0,1], [1,0,0,1,0,0,0,1,0,1], [1,0,0,0,0,1,1,0,0,1], [1,0,1,1,1,0,0,0,0,1], [1,0,0,0,1,0,0,0,0,1], [1,0,1,0,0,0,1,0,0,1], [1,0,1,1,1,0,1,1,0,1], [1,1,0,0,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1] ]
dirs=[ lambda x,y:(x+1,y), lambda x,y:(x-1,y), lambda x,y:(x,y-1), lambda x,y:(x,y+1), ] def maze_path_DFS(x1,y1,x2,y2): stack=[] stack.append((x1,y1)) while(len(stack)>0): curNode=stack[-1] if curNode[0]==x2 and curNode[1]==y2: for p in stack: print(p) return True for dir in dirs: nextNode=dir(curNode[0],curNode[1]) if maze[nextNode[0]][nextNode[1]]==0: stack.append(nextNode) maze[nextNode[0]][nextNode[1]] =2 break else: maze[nextNode[0]][nextNode[1]] =2 stack.pop() else: print("没有路径") return False
maze_path_DFS(1,1,8,8)
maze=[ [1,1,1,1,1,1,1,1,1,1], [1,0,0,1,0,0,0,1,0,1], [1,0,0,1,0,0,0,1,0,1], [1,0,0,0,0,1,1,0,0,1], [1,0,1,1,1,0,0,0,0,1], [1,0,0,0,1,0,0,0,0,1], [1,0,1,0,0,0,1,0,0,1], [1,0,1,1,1,0,1,1,0,1], [1,1,0,0,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1] ]
dirs=[ lambda x,y:(x+1,y), lambda x,y:(x-1,y), lambda x,y:(x,y-1), lambda x,y:(x,y+1), ]
def maze_path_BFS(x1,y1,x2,y2): from collections import deque def print_p(path): curNode = path[-1] realpath = [] while curNode[2] != -1: realpath.append(curNode[0:2]) curNode = path[curNode[2]] realpath.append(curNode[0:2]) realpath.reverse() for node in realpath: print(node) queue=deque() queue.append((x1,y1,-1)) path=[] while len(queue)>0: curNode=queue.popleft() path.append(curNode) if curNode[0]==x2 and curNode[1]==y2: print_p(path) return True for dir in dirs: nextNode=dir(curNode[0],curNode[1]) if maze[nextNode[0]][nextNode[1]]==0: queue.append((nextNode[0],nextNode[1],len(path)-1)) maze[nextNode[0]][nextNode[1]] =2
else: print("没有路径") return False maze_path_BFS(1,1,8,8)
|