2017-03-09 93 views
0

我有一個程序尋找從一個位置到另一個位置的網格中的最短路徑。有沒有辦法執行所有可能的語句?

我認爲返回的最短路徑將取決於函數首先調用數組中的哪個方向。

有沒有辦法讓相同的功能運行在下面,除了一次對於北,南,東,西的每個可能的順序?

我明白我可以有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) 

回答

0

我Python是有點生疏了,所以別人也許是在給你確切的語法更好,但原則上,你需要創建一個類似如下的功能:

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

然後根據需要用chkX,chkY替換那些-1和+1值。

然後你只需調用該函數的4倍,看起來像這樣:

checkDir(1, 1) 
checkDir(-1, 1) 
checkDir(1, -1) 
checkDir(-1, -1) 
+0

我覺得應該是'checkDir(1,0)','checkDir(-1,0)','checkDir( 0,1)'和'checkDir(0,-1)'。此外,要查找並選擇所有排列,請考慮'list(itertools.permutation([(1,0),( - 1,0),(0,1),(0,-1)]))''。 –

相關問題