def ShortestDistance(maps,i,j,short,k): #i,j-->current position.
x=0
y=0
for a in range(0, len(maps)):
for b in range(0, len(maps[0])):
if maps[a][b] == 2:
x = a
y = b
if (i==x) and (j==y):
short=min(short,k)
return short
maps[i][j]=3
if within(i+1,j) and possible(maps,i+1,j):
return ShortestDistance(maps,i+1,j,short,k+1)
if within(i, j+1) and possible(maps,i, j+1):
return ShortestDistance(maps,i,j+1,short,k+1)
if within(i-1,j) and possible(maps,i-1,j):
return ShortestDistance(maps,i-1,j,short,k+1)
if within(i,j-1) and possible(maps,i,j-1):
return ShortestDistance(maps,i,j-1,short,k+1)
maps[i][j]=0
result=ShortestDistance(maps,0,0,longest,0)
if result is None:
answer=-1
else:
answer=result
我在这里要做的是使函数遍历函数中的所有if语句,而不管先前的if语句是否为true。 例如,我希望代码中的第三个if语句也可以通过,即使第二个为true(在这种情况下,计算机似乎也没有经过第三个)。 我的最终目标是为所有可能的情况找到k的最小值。 我将如何使其成为可能?
答案 0 :(得分:0)
使用这个:
def ShortestDistance(maps,i,j,short,k): #i,j-->current position.
x=0
y=0
for a in range(0, len(maps)):
for b in range(0, len(maps[0])):
if maps[a][b] == 2:
x = a
y = b
if (i==x) and (j==y):
short=min(short,k)
return short
maps[i][j]=3
resx = []
if within(i+1,j) and possible(maps,i+1,j):
resx.append(ShortestDistance(maps,i+1,j,short,k+1))
if within(i, j+1) and possible(maps,i, j+1):
resx.append(ShortestDistance(maps,i,j+1,short,k+1))
if within(i-1,j) and possible(maps,i-1,j):
resx.append(ShortestDistance(maps,i-1,j,short,k+1))
if within(i,j-1) and possible(maps,i,j-1):
resx.append(ShortestDistance(maps,i,j-1,short,k+1))
maps[i][j]=0
return min(resx)
result=ShortestDistance(maps,0,0,longest,0)
if result is None:
answer=-1
else:
answer=result
答案 1 :(得分:0)
请注意return
语句。一旦函数遇到一个,它就会退出。
尝试这样的事情:
def ShortestDistance(maps,i,j,short,k):
#...
distances = []
if within(i+1,j) and possible(maps,i+1,j):
distances.append(ShortestDistance(maps,i+1,j,short,k+1))
if within(i, j+1) and possible(maps,i, j+1):
distances.append(ShortestDistance(maps,i,j+1,short,k+1))
if within(i-1,j) and possible(maps,i-1,j):
distances.append(ShortestDistance(maps,i-1,j,short,k+1))
if within(i,j-1) and possible(maps,i,j-1):
distances.append(ShortestDistance(maps,i,j-1,short,k+1))
return min(distances)