【问题标题】:Validation function for not crossing the boundaries of a matrix (maze)不跨越矩阵边界的验证函数(迷宫)
【发布时间】:2018-08-22 08:39:42
【问题描述】:

假设您在 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 语句,以便您可以更轻松地检查输入?

【问题讨论】:

    标签: validation matrix maze


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多