如何使用python动画演示深度优先算法搜寻逃出迷宫的路径创新互联

十年网站开发经验+多家企业客户+靠谱的建站团队

量身定制+运营维护+专业推广+无忧售后,网站问题一站解决

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

深度优先算法(DFS算法)是什么?

寻找起始节点与目标节点之间路径的算法,常用于搜索逃出迷宫的路径。主要思想是,从入口开始,依次搜寻周围可能的节点坐标,但不会重复经过同一个节点,且不能通过障碍节点。如果走到某个节点发现无路可走,那么就会回退到上一个节点,重新选择其他路径。直到找到出口,或者退到起点再也无路可走,游戏结束。当然,深度优先算法,只要查找到一条行得通的路径,就会停止搜索;也就是说只要有路可走,深度优先算法就不会回退到上一步。

下图是使用DFS算法搜寻出来的一条路径:

总结一下:

从起点开始,查询下一步走得通的节点,将这些可能的节点压入堆栈中,已经走过的节点不再尝试。查询完毕之后,从堆栈中取出一个节点,查询该节点周围是否存在走得通的节点。如果不存在可能的节点,就继续从堆栈中取一个节点。重复以上操作,直到当前节点为终点,或者堆栈中再无节点。

定义数据:

定义辅助函数

首先,我们来定义栈这种数据结构,栈是一种后进先出的数据结构。

#find_path.pyfromutilsimportStackdefdfs(initial,_next=successor,_test=test_goal):s:Stack=Stack()marked={initial}s.push(initial)whiles:parent:state=s.pop()if_test(parent):returnparentchildren=_next(parent)forchildinchildren:ifchildnotinmarked:marked.add(child)s.push(child)接下来,我们使用DFS算法寻找迷宫路径,并对搜寻到的迷宫路径进行可视化演示。

首先使用枚举,来表示路径的颜色,EMPTY为正常节点,BLOCKED为障碍节点,START为迷宫入口,END为迷宫出口,PATH为搜寻的路径。

fromenumimportIntEnumclassCell(IntEnum):EMPTY=255BLOCKED=0START=100END=200PATH=150接下来,我们来定义迷宫。首先,我们采用Namedtuple来定义迷宫每个节点的坐标:

classMazeLocation(NamedTuple):row:intcol:int首先为了方便确定节点之间的关系,我们在Maze类中定义了一个内部类_Node,用来记录节点的状态,及节点的父节点。

class_Node:def__init__(self,state,parent):self.state=stateself.parent=parent接着初始化,确定入口与出口的坐标,使用np.random.choice函数随机生成迷宫,并标记入口和出口。

def__init__(self,rows:int=10,cols:int=10,sparse:float=0.2,seed:int=365,start:MazeLocation=MazeLocation(0,0),end:MazeLocation=MazeLocation(9,9),*,grid:Optional[np.array]=None)->None:np.random.seed(seed)self._start:MazeLocation=startself._end:MazeLocation=endself._grid:np.array=np.random.choice([Cell.BLOCKED,Cell.EMPTY],(rows,cols),p=[sparse,1-sparse])self._grid[start]=Cell.STARTself._grid[end]=Cell.END其次是test_goal方法,只要该节点坐标与目标节点相即可。

def_test_goal(self,m1:MazeLocation)->bool:returnm1==self._end再就是successor方法,只要上下左右方向的节点不是障碍节点且在边界之内,就纳入考虑范围,加入列表之中。

List[MazeLocation]:location:List[MazeLocation]=[]row,col=self._grid.shapeifm1.row+1=0andself._grid[m1.row-1,m1.col]!=Cell.BLOCKED:location.append(MazeLocation(m1.row-1,m1.col))ifm1.col+1=0andself._grid[m1.row,m1.col-1]!=Cell.BLOCKED:location.append(MazeLocation(m1.row,m1.col-1))returnlocation显示路径,pause为显示图像的间隔,plot为是否绘图标志。通过目标节点出发,遍历每一个节点的父节点,直到到达初始节点,并绘制路径图。

THE END
1.Python错题整理importmath result=math.isclose(2.1-2,0.1) 1 2 3 这样可以避免因浮点数精度问题导致的错误判断。 结论 由于浮点数精度问题,2.1 - 2不一定等于0.1,所以原命题是错误的。答案应为 F。 题目 Python中的成员运算符用于判断指定序列中是否包含某个值。 https://blog.csdn.net/xiaoyushashasha/article/details/144435477
2.python基础重点知识点笔记Python基础期末考试试题及答案(完整版)python基础重点梳理笔记.pdf Python2020期末考试试题及答案,pdf Python基础试题(含答案).pdf python基础试题(含答案)图文,pdf 1.Python应用基础 迅雷云盘?pan.xunlei.com/s/VODsrj__HDu4mqfWHp-oUwfSA1?pwd=fyba# Python变量和数据类型 https://zhuanlan.zhihu.com/p/12192479944
3.aiohttp.client—googleimport hdrs, http, payload from .abc import AbstractCookieJar from .client_exceptions import ClientConnectionError as ClientConnectionError from .client_exceptions import ( ClientConnectorCertificateError as ClientConnectorCertificateError, ) from .client_exceptions import ClientConnectorError as ClientConnectorhttps://googleapis.dev/python/google-auth/1.22.0/_modules/aiohttp/client.html
4.tornado.gen—Tornado5.1.1documentation[docs]defcoroutine(func):"""Decorator for asynchronous generators.Any generator that yields objects from this module must be wrappedin either this decorator or `engine`.Coroutines may "return" by raising the special exception`Return(value) <Return>`. In Python 3.3+, it is also possible forthehttps://www.tornadoweb.org/en/branch5.1/_modules/tornado/gen.html
5.python中级知识.md·空虚的心/blogfrom abc import ABCMeta, abstractmethod #抽象主题 class Oberserver(metaclass=ABCMeta): @abstractmethod def update(self): pass #具体主题 class Notice: def __init__(self): self.observers = [] def attach(self,obs): self.observers.append(obs) def detach(self,obs): self.observers.remove(obs)https://gitee.com/kongxudexin/blog/blob/master/python%E4%B8%AD%E7%BA%A7%E7%9F%A5%E8%AF%86.md
6.typing—bidict0.21.3documentationWrapper submodules for re and io related types."""fromabcimportabstractmethod,ABCMetaimportcollectionsimportcollections.abcimportcontextlibimportfunctoolsimportoperatorimportreasstdlib_re# Avoid confusion with the re we export.importsysimporttypesfromtypesimportWrapperDescriptorType,MethodWrapperType,Methodhttps://bidict.readthedocs.io/en/v0.21.3/_modules/typing.html
7.天津网站建设泰姆仕/宁波seo优化公司排名(3)abc里面所有的抽象基类 fromcollections.abcimport* 所有的抽象基类 #Copyright 2007 Google, Inc. All Rights Reserved.#Licensed to PSF under a Contributor Agreement."""Abstract Base Classes (ABCs) for collections, according to PEP 3119.Unit tests are in test_collections."""fromabcimportABCMeta,http://www.mhkc.cn/news/832195.html
8.Python中应用protobuf的示例详解pythonfrom abc import ABC from tornado import web, ioloop import girl_pb2 class GetInfoHandler(web.RequestHandler, ABC): async def post(self): # 拿到客户端传递的字节流 # 这个字节流应该是由 girl_pb2.Request() 序列化得到的 content = self.request.body # 下面进行反序列化 request = girl_pb2.Rehttps://www.jb51.net/article/275753.htm
9.Python进阶Python中的自定义装饰器:打造可重用的函数修饰from abc import ABC, abstractmethod # 抽象产品类 class Animal(ABC): @abstractmethod def make_sound(self): pass # 工厂类 class AnimalFactory: @staticmethod def create_animal(animal_type): if animal_type == "dog": return Dog() elif animal_type == "cat": https://cloud.tencent.com/developer/news/1353778
10.python2.6的新功能—Python3.10.0a4文档明智地检查abc,并且只在绝对必要的地方进行。 您可以使用 abc.ABCMeta 作为类定义中的元类: from abc import ABCMeta, abstractmethod class Drawable(): __metaclass__ = ABCMeta @abstractmethod def draw(self, x, y, scale=1.0): pass def draw_doubled(self, x, y): self.draw(x, y, scale=2.0https://www.osgeo.cn/cpython/whatsnew/2.6.html
11.Python基础(2)from abc import ABCMeta, abstractmethod class Super(metaclass = ABCMeta): @abstractmethod def action(self): pass x = Super() # 返回 TypeError: Can't instantiate abstract class Super with abstract methods action #-- # OOP和继承: "is-a"的关系 class Ahttps://www.jianshu.com/p/904b914cd3f6
12.FastApi(自用脚手架)+Snowy搭建后台管理系统(6)脚手架from abc import ABC, abstractmethod from typing import Union, Tuple from snowy_src.snowy_system.snowy_modules.auth.schemas import AuthAccountPasswordLoginParam, \ AuthPhoneValidCodeLoginParam from fastapi import Request class IAuthService(ABC): https://blog.itpub.net/70041327/viewspace-3037631/
13.elementplusimport所有语言mob64ca1400bfa8的技术博客elementplus import所有语言 第三章 栈、队列和数组 一、栈 栈是只能在一端进行插入和删除的线性表。 (别看只是个定义,非常重要,已经道出了运算方法:只能在一端插入和删除。) 栈的特征:后进先出,先进后出。 插入和删除元素的一端称为栈顶。(说明了我们在栈顶操作)https://blog.51cto.com/u_16213618/12794215
14.字符串の宝典name = 'abcdef' print(name[0]) print(name[1]) print(name[2]) # 索引是通过下标取某一个元素 # 切片是通过下标去某一段元素 s = 'Hello World!' print(s) print(s[4]) # o 字符串里的第4个元素 print(s[3:7]) # lo W 包含下标 3,不含下标 7 https://www.bilibili.com/read/cv39995475
15.What’sNewinPython2.6—Python3.13.1documentationYou can write your own ABCs by using abc.ABCMeta as the metaclass in a class definition: from abc import ABCMeta, abstractmethod class Drawable(): __metaclass__ = ABCMeta @abstractmethod def draw(self, x, y, scale=1.0): pass def draw_doubled(self, x, y): self.draw(x, y, scalehttps://docs.python.org/whatsnew/2.6.html
16.实例化类时abstractmethod()的作用和影响分析from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height https://www.6qe.net/amg-article-131069-kp2lv4otuS.html
17.2.7.0详细内容见gitee·thomasjimmyfrom abc import abstractmethod from re import sub from typing import Union, Tuple, List from urllib.parse import quote from lxml.html import HtmlElement from selenium.webdriver.remote.webelement import WebElement @@ -330,6 +331,18 @@ def url_available(self) -> bool: """返回当前访问的url有https://github.com/thomas-jimmy-chen/DrissionPage/commit/2ca706c2f465a41479bcb8fd96ab431d68059883
18.python爬虫思维导图模板fromcollections.abcimportIterable print(isinstance([],Iterable)) >>True zip() zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表 字典 1.键值对,键不可以重复,值可以重复 2.元素是无序的 https://www.processon.com/view/6348e3687d9c080c42558dc6
19.ExtinguisherSizesofMarineSafetyandLifesavingfromQuality Marine Stainless Steel ABC Type Co2 Fire Extinguisher Sizes - find quality Marine Safety and Lifesaving, Fire Extinguisher & Marine Safety and Lifesaving from Chongqing B.M. Import & Export Trading Co., Ltd. of China Suppliers - 138511233.https://detail.en.china.cn/provide/p138511233.html
20.使用abc.def包中的所有类的方法可行的有()A. 组织单元为行,工作单元为列 B. 工作单元为行,绢织单元为列 C. 合同单元为行,活动单元为列 D. 活动单元为行,合同单元为列 查看完整题目与答案 参考解析: 设置CLASSPATH=/abc/def;源文件加入importabc.def.*;每个使用abc.def类的地方,在类名前加上abc.def AI解析 重新生成最新https://www.shuashuati.com/ti/37873e474a124645bd49900b68cec28e.html?fm=bdbds20956e29d77949e14ab490f3fd8c7ed0
21.国际贸易实务双语教程练习答案解析But as a form of international trade, it is still attractive in developing countries where foreign exchange is in short supply and inflow of foreign funds is far from sufficient to meet their obligations in external trade. Unit 2 General Procedures of Export and Import Transaction I. Answer thehttps://easylearn.baidu.com/edu-page/tiangong/exercisedetail?id=f541b7fea22d7375a417866fb84ae45c3a35c279&fr=search