首页 > 解决方案 > 不跨越矩阵边界的验证函数(迷宫)

问题描述

假设您已经在 Python 中编写了 amxn 矩阵。不可能有矩阵之外的值。假设你是在矩阵中移动的东西(比如在迷宫中),并且你不能跨越边界。当你在迷宫中移动时,你会不断地考虑你可以走哪条路。因此,对于每一步,您都需要检查是否可以朝各个方向前进,或者是否有无法跨越的界限。

因此,考虑一个需要检查下一步输入是否可能的函数。如果输入是矩阵中的位置(x,y),那么它需要检查它是否可以在不跨越矩阵边界的情况下向各个方向移动。所以它需要检查位置(x+1,y),(x-1,y),(x,y-1),(x,y+1)是否还在矩阵中。

您可以使用许多 if 语句来创建此功能,例如
if x-1 < 0: return False

elif y+1 > len(matrix): return False

您可以为每个方向制作这些 if 语句,但在我看来,仅检查输入就需要做很多工作。是否有内置函数或矩阵的属性或更简单的 if 语句,以便您可以更轻松地检查输入?

标签: validationmatrixmaze

解决方案


这取决于您使用的语言,但大多数情况下我编写代码来检查这样的相邻位置(如果我们不将对角线计算为相邻):

//given current position in x and y...

int dx=1, dy=0; //first check to the right
for (int i=0; i<4; i++)
{
    int testx = dx, testy = dy; //remember current direction
    dx = -testy; dy = testx;    //next direction is rotated 90 degrees
    testx += x; testy += y;     //new position to test
    if (testx>=0 && testx<width && testy>=0 && testy<height)
    {
        //this position is within the matrix.  do other checks and stuff
    }
}

如果你也想检查对角线,那么我经常做这样的事情:

//given current position in x and y...

for (int dy=-1; dy<=1; ++dy)
{
    for(int dx=-1; dx<=1; dx+=(dy==0?2:1))
    {
        int testx = x+dx, testy = y+dy; //new position to test
        if (testx>=0 && testx<width && testy>=0 && testy<height)
        {
            //this position is within the matrix.  do other checks and stuff
        }
    }
}

编辑:

哦,我只是想到了一种新的方法来处理 4 路邻接情况,我想我将从现在开始使用它(你会获得支持!)。此代码按顺时针顺序生成 4 个相邻位置:

//given current position in x and y...

for (int i=0; i<4; ++i)
{
    int dse = (i>>i)&1;
    int dsw = (i^dse)&1;
    int testx = x+dsw-dse, testy = y+1-dsw-dse; //new position to test
    if (testx>=0 && testx<width && testy>=0 && testy<height)
    {
        //this position is within the matrix.  do other checks and stuff
    }
}

推荐阅读