python - 如何修复构建可见性图的算法?

标签 python algorithm geometry path-finding

我正在尝试编写一个代码,从一组点和墙壁(障碍物)生成可见性图。我的算法不正确,并且在某些情况下会失败,因为两点之间有不止一堵墙与边相交。

这是我的算法的一种伪 python 代码:

Intersect(wall, P, Q):
    returns True if wall segment intersects with PQ segment

Cross(wall, P, Q):
    returns True if wall segment crosses PQ segment

for i in range(len(nodes)):
    for j in range(i + 1, len(nodes)):
        flag = True
        for wall in walls:
            if (Cross(wall, nodes[i].pos, nodes[j].pos)):
                flag = False
        if (flag):
            nodes[i].adj.append(nodes[j])
            nodes[j].adj.append(nodes[i])

如何修复我的算法?

这是它失败的测试之一:

墙壁:

w1 -> (1, 0),(2, 1)
w2 -> (2, 1),(3, 2)

要检查的节点:

node1 -> (0, 2)
node2 -> (4, 0)

不应该有边,但我的算法生成了边,因为边不穿过任何墙(它相交但不交叉)。

为了澄清,Cross 表示两个线段相交(共享一个点),但它们不共享任何两个线段的起点或终点。

最佳答案

当观察光线像这样擦过墙时,您需要跟踪擦过是在墙的左边缘还是右边缘,如从视点 P 所见。

def LeftIntersect(wall, P, Q):
    if Cross(wall, P, Q):
        return False
    if not Intersect(wall, P, Q):
        return False
    if magnitude(cross_product(PQ, wall_midpoint)) <= 0:
        return False
    return True

def RightIntersect(wall, P, Q):
    if Cross(wall, P, Q):
        return False
    if not Intersect(wall, P, Q):
        return False
    if magnitude(cross_product(PQ, wall_midpoint)) >= 0:
        return False 
    return True

for i in range(len(nodes)):
    for j in range(i + 1, len(nodes)):
        crossCount = 0
        leftIntersectCount = 0
        rightIntersectCount = 0
        for wall in walls:
            if (Cross(wall, nodes[i].pos, nodes[j].pos)):
                crossCount += 1
            if (LeftIntersect(wall, nodes[i].pos, nodes[j].pos)):
                leftIntersectCount += 1
            if (RightIntersect(wall, nodes[i].pos, nodes[j].pos)):
                rightIntersectCount += 1
        visible = True
        if (crossCount > 0)
            visible = False
        if (leftIntersect > 0 && rightIntersect > 0)
            visible = False        
        if (visible):
            nodes[i].adj.append(nodes[j])
            nodes[j].adj.append(nodes[i])

关于python - 如何修复构建可见性图的算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54101717/

相关文章:

algorithm - 两个字符串所有可能的LCS(Longest Common Subsequence)

python - 定位球形多边形的质心(质心)

python - 在python中将url编码的字符串(utf-8)转换为字符串?

Python BaseHTTPRequestHandler : Respond with JSON

python - 分配简单变量命名后出现 KeyError

python - Pandas 数据框条件 .mean() 取决于特定列中的值

javascript - 检测 Canvas 边缘并允许远离它的移动

c++ - 给定一个单词,通过在它们之间添加空格来形成一个有意义的单词

geometry - 在postgis中,Z-Dimension和M-Dimension有什么区别

c# - 删除大数据集的关闭点 C#