我想弄清楚如何终止递归函数。如下图所示:
getEmpty[9]
将返回:
[6,10]
但是我需要它来返回[6,8,9,10,11]
因为我想要所有空箱,只要它与前一个空箱共享边缘。
如何终止此递归?
目前我有
getEmpty(9)
#my code here
return empties;
empties = [6,10]
我补充说:
for cell in empties:
if(getEmpty(cell) not in empties):
empties = empties+getEmpty(cell)
最后,但它给了我一个打印出来的无限循环:
[6,10]
[9]
不停,我该如何解决这个问题?
答案 0 :(得分:4)
编辑:抱歉,您的问题非常含糊不清。你需要的是一个简单的图遍历算法。这是对它的一瞥:
input : coordinate of a cell
function empty_cell_search(cell)
for neighbor_cell in neighbors :
if the_neighbor_cell is empty and is not already visited :
add the_neighbor_cell to set of visited cells
union empty_cell_search(the_neighbor_cell) with current set of visited cells
return the set of currently visited cells
答案 1 :(得分:1)
你应该使用它(python 3,但2的想法相同):
empty=[6,8,9,10,11]
start=9
done=[int(start)]
while True:
complete=True
for num0 in empty:
for num1 in done:
if (abs(num0-num1)==1 or abs(num1-num0)==3) and num0 not in done:
complete=False
done.append(num0)
if complete=True:
break
print(sorted(done))