不跨越矩阵边界的验证函数(迷宫)

Validation function for not crossing the boundaries of a matrix (maze)

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

因此考虑一个需要检查下一步输入是否可行的函数。如果输入是矩阵中的位置 (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 语句以便您可以更轻松地检查输入?

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

//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
    }
}