我正在努力适应这个
solution
到代码阻塞
Dice Straight
Python的问题。不幸的是,它需要太深的递归才能在Python中正常工作(除非递归限制和堆栈大小都显著增加)。所以我想把这个递归
method
要迭代:
boolean freeByShuffling(Die die) {
assert die.valueUsing != null;
for (Die otherDie : die.valueUsing.dice) {
if (otherDie.valueUsing == null) {
otherDie.valueUsing = die.valueUsing;
die.valueUsing = null;
return true;
}
}
diceVisitedWhileShuffling.add(die);
for (Die otherDie : die.valueUsing.dice) {
if (diceVisitedWhileShuffling.contains(otherDie)) continue;
if (freeByShuffling(otherDie)) {
otherDie.valueUsing = die.valueUsing;
die.valueUsing = null;
return true;
}
}
return false;
}
这是我的Python代码,虽然它解决了大多数测试用例,但效果并不理想:
def free_by_shuffling(self, die):
assert die.current_value is not None
stack = [(None, die)]
found = False
while stack:
this_die, other_die = stack.pop()
self.visited.add(other_die)
if found:
other_die.current_value = this_die.current_value
this_die.current_value = None
continue
for next_die in other_die.current_value.dice:
if next_die in self.visited:
continue
if next_die.current_value is None:
found = True
stack.append((other_die, next_die))
break
else:
for next_die in other_die.current_value.dice:
if next_die in self.visited:
continue
stack.append((other_die, next_die))
return found
如何将原始方法转换为使用迭代而不是递归?