用Python制作迷宫图
嘿,我正在尝试使用 Python 中的字典制作图表。我正在使用一个包含迷宫的 txt 文件(b 代表墙壁,a 代表路径),我正在尝试制作一个字典,列出在迷宫中采取的所有可能的动作(简单的步骤,而不是完整路径)。我应该从哪里开始有什么想法吗?我从来没有使用过字典。
非常感谢您的帮助,这让我有了一个良好的开端。还有一个问题,我从一栋有效的房子开始,检查所有可能的路径。之后我必须搬到另一所房子并检查那里的路径。我怎样才能确保我不会出现无限循环或重新检查已经检查过的房子?
Hey, I'm trying to make a graph using dictionaries in Python. I'm using a txt
file containing a maze (b for walls a for paths) and I'm trying to make a dictionary that lists all the possible moves to take in a maze (simple steps, not full paths). Any ideas on where I should start? I never worked with dictionaries.
Thank you so much for you help, that got me off on a great start. Just one more question, I'm starting at one valid house and checking all possible paths. after that ill have to move to another house and check the paths on that. How can i make sure i dont get an infinite loop or recheck a house ive already checked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您的迷宫看起来像一个网格,迷宫中的位置可以表示为元组 (row,col)。当您构建字典时,为迷宫中的每个位置创建一个条目,初始值是一个空列表。在迷宫中的每个有效位置 (r,c),计算是否可以到达 (r-1,c)、(r,c-1)、(r+1,c) 和 (r,c+) 1)。如果可以的话,将该元组添加到列表中。所以,假设我可以从 (r,c) 到达 (r-1,c) 和 (r,c+1),字典中的条目看起来像
要创建一个空字典,您可以使用:
您还应该查看 python 教程的 字典 部分
Assuming that your maze looks like a grid, a position in the maze could be represented as a tuple (row,col). When you construct your dictionary, create an entry for every position in the maze, the initial value is an empty list. At every valid position (r,c) in the maze, figure out if you can get to (r-1,c), (r,c-1), (r+1,c), and (r,c+1). If you can, then add that tuple to the list. So, let's say that I can get to (r-1,c) and (r,c+1) from (r,c), the entry in the dictionary would look like
To create an empty dictionary, you'd use:
You should also take a look at the dictionaries section of the python tutorial
创建一个“House”类,及其网格坐标:
创建一些房屋:
现在,遍历每个房屋,并计算其路径
逐步浏览列表可确保您仅检查每个房屋一次。现在您可以找出无法到达的房屋:
Create a "House" class, with its grid coordinates:
Create some houses:
Now, go through each house, and caculate its path(s)
Stepping through the list ensures that you check each house only once. Now you can find out the houses that are unreachable: