有没有办法执行所有可能的语句顺序?

时间:2017-03-09 15:27:51

标签: python

我有一个程序在网格中寻找从一个位置到另一个位置的最短路径。

我认为返回的最短路径将取决于函数首先调用的数组中的哪个方向。

有没有办法让相同的功能运行如下,除了北,南,东,西的每个可能的顺序一次?

我知道我可以有4个!类似的功能,但我想知道是否有更清洁的方法。

为了我的无知而提前道歉,我并不是特别有经验!

def find_path(world, path, robotx, roboty, goalx, goaly, size):
print("Robot at: ", robotx, ",", roboty)
#print(path)
time.sleep(0.7)
if [robotx, roboty] == [goalx, goaly]:
    path_count = 0
    print("Woohoo! Goal found at ", goalx, ',', goaly, '. ', "Steps taken: ", path_count)
    print(path)
    return path
else:
    #South
    if robotx != size and world[robotx + 1][roboty] in (0, 2):
        world[robotx + 1][roboty] = 3
        path.add_head(Node([robotx + 1, roboty]))
        find_path(world, path, robotx + 1, roboty, goalx, goaly, size)

    #East
    if roboty != size and world[robotx][roboty + 1] in (0, 2):
        world[robotx][roboty + 1] = 3
        path.add_head(Node([robotx, roboty + 1]))
        find_path(world, path, robotx, roboty + 1, goalx, goaly, size)

    #North
    if robotx != 0 and world[robotx - 1][roboty] in (0, 2):
        world[robotx - 1][roboty] = 3
        path.add_head(Node([robotx - 1, roboty]))
        find_path(world, path, robotx - 1, roboty, goalx, goaly, size)

    #West
    if roboty != 0 and world[robotx][roboty - 1] in (0, 2):
        world[robotx][roboty - 1] = 3
        path.add_head(Node([robotx, roboty - 1]))
        find_path(world, path, robotx, roboty - 1, goalx, goaly, size)

1 个答案:

答案 0 :(得分:0)

我的Python有点生疏,所以其他人可能更擅长为您提供确切的语法,但原则上,您需要创建一个如下所示的函数:

def checkDir( chkX, chkY):
    ...
return

然后根据需要用chkX,chkY替换那些-1和+1值。

然后你只需要调用该函数4次,如下所示:

checkDir( 1, 1)
checkDir( -1, 1)
checkDir( 1, -1)
checkDir( -1, -1)
相关问题