2代表起点,1代表障碍,3代表终点,空处为0
2 | 1 | ||
1 | |||
1 | 1 | 3 | |
1 |
求到达终点的最短路径
1,深度优先搜索
m=[ [0,0,1,3], [1,0,0,0], [0,1,0,1], [1,1,0,0], [1,0,0,1]] #path标记已走过的路 def dfs(path,cX=0,cY=0,): if m[cX][cY]==3: return True next=[(0,1),(1,0),(-1,0),(0,-1)] for n in next: nX=cX+n[0] nY=cY+n[1] #判断是否超出边界 if nX>=0 and nX<=4 and nY>=0 and nY<=3: #判断是否是障碍或原路径 if m[nX][nY]!=1 and (nX,nY) not in path: path.append((nX,nY)) print(nX,nY) if dfs(path,nX,nY): return True path.pop() #如果一条路走不通,就把它弹出标记 p=[] dfs(p) print(p)
2,广度优先搜索
BFS优化策略,其实不必删除列表第一项,否则列表会重新进行O(n)的复杂度排列,队列出队优化其实用双指针就可以,一个指向当前队首,一个指向队尾
m=[ [0,0,1,3], [1,0,0,0], [0,1,0,1], [1,1,0,0], [1,0,0,1]] def bfs(sX=0,sY=0): queue=[] path={} nbr=[(0,1),(1,0),(-1,0),(0,-1)] queue.append((sX,sY)) path[(0,0)]=None stop=False while not stop: for n in nbr: nX=queue[0][0]+n[0] nY=queue[0][1]+n[1] if nX>=0 and nX<5 and nY>=0 and nY<4: if m[nX][nY]!=1 and (nX,nY) not in queue and (nX,nY) not in path: queue.append((nX,nY)) path[(nX,nY)]=queue[0] if m[nX][nY]==3: print("xxx") tmp=(nX,nY) true_path=[] while tmp in path: true_path.append(tmp) tmp=path[tmp] print(list(reversed(true_path))) stop=True break del queue[0] bfs()