python - Python中连接两个坐标的多米诺骨牌路径

标签 python sorting path coordinates maze

上下文

我正在尝试创建一个迷宫解析器。

maze

问题

是否可以对 [x, y] 坐标列表进行排序和过滤,或多或少像多米诺骨牌一样,连接 2 个已知坐标?

输入

# [2, 2] is start
# [6, 2] is end
[[2, 2], [4, 2], [5, 2], [2, 3], [4, 3], [2, 4], [3, 4], [4, 4], [2, 5], [4, 5], [5, 5], [6, 2]]

想要的输出

# Shortest path from Start to End
[[2, 2], [2, 3], [2, 4], [3, 4], [4, 4], [4, 3], [4, 2], [5, 2], [6, 2]]

最佳答案

目前,解决我的问题的最佳方法是在这篇文章中找到的: Get shortest path to a cell in a 2d array python

这是我使用给定代码的方式。它工作完美:

import collections

start = (2, 2)
end = (6, 2)
grid = [(2, 2), (4, 2), (5, 2), (2, 3), (4, 3), (2, 4), (3, 4), (4, 4), (2, 5), (4, 5), (5, 5), (6, 2)]

queue = collections.deque([[start]])
seen = set(start)

while queue:
    path = queue.popleft()
        (x, y) = path[-1]
        if (x, y) == end:
            return path
        for x2, y2 in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
            if (x2, y2) not in seen and (x2, y2) in grid:
                queue.append(path + [(x2, y2)])
                seen.add((x2, y2)) 
print(path)
# path is [(2, 2), (2, 3), (2, 4), (3, 4), (4, 4), (4, 3), (4, 2), (5, 2), (6, 2)]

关于python - Python中连接两个坐标的多米诺骨牌路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59772072/

相关文章:

Python - 如何在 Ubuntu 上的根文件夹中打开或创建文件?

c - ANSI C 中的字符串处理

arrays - k 使用插入排序打乱排序数组

javascript - Jquery 用数字排序表数据

python - 如何在Python中停止另一个进程

python - Django 无法识别 MEDIA_URL 路径?

javascript - 在 knockout js 或 javascript 中用斜杠对数字进行排序

c - 如何找到文件的完全限定路径名?

python - 无法在纯 CPU Caffe 中使用 GPU : check mode

python - 如何计算标签/工具提示的聚合的聚合?