验证功能,用于不跨越矩阵(迷宫)的边界



假设你已经用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
}
}

最新更新