我以为我的代码没有问题,但是当我开始更改值时,我最终遇到了递归问题。我以为我修复了它,但是当我查看结果时,它们都错了。不过,当我保持递归时,结果很好。
我使用了一个while循环来尝试解决递归问题,而不是递归地调用spread方法,我将传递给它的值返回给propagate方法,如果它不传递值则返回False。因此,只要该方法不断返回值,它就应该使用前一次运行的结果重新运行 spread 方法。
此代码一直有效,直到它打破递归限制:
def spread(self, position):
for direction in self._directions:
(x, y) = self.changePosition(position, direction)
if self.canInfectMatrix[x][y] and not self.contactMatrix[x][y]:
self.contactMatrix[x][y] = True
self.spread([x,y])
# return [x,y]
# return False
def propagate(self):
# initialize canInfectMatrix and contactMatrix
self.contactMatrix = [[False for row in range(self.cardinalWidth)] for col in range(self.cardinalWidth)]
self.canInfectMatrix = [[False for row in range(self.cardinalWidth)] for col in range(self.cardinalWidth)]
for col in range(self.cardinalWidth):
for row in range(self.cardinalWidth):
self.canInfectMatrix[row][col] = self.getsInfected(self._matrix[col][row])
# Spread infection.
for x in range(self.cardinalWidth):
for y in range(self.cardinalWidth):
if self._matrix[x][y] == "infected":
self.spread([x,y])
# position = [x,y]
# while position:
# position = self.spread(position)
以下代码不起作用,但我没有收到错误:
def spread(self, position):
for direction in self._directions:
(x, y) = self.changePosition(position, direction)
if self.canInfectMatrix[x][y] and not self.contactMatrix[x][y]:
self.contactMatrix[x][y] = True
# self.spread([x,y])
return [x,y]
return False
def propagate(self):
# initialize canInfectMatrix and contactMatrix
self.contactMatrix = [[False for row in range(self.cardinalWidth)] for col in range(self.cardinalWidth)]
self.canInfectMatrix = [[False for row in range(self.cardinalWidth)] for col in range(self.cardinalWidth)]
for col in range(self.cardinalWidth):
for row in range(self.cardinalWidth):
self.canInfectMatrix[row][col] = self.getsInfected(self._matrix[col][row])
# Spread infection.
for x in range(self.cardinalWidth):
for y in range(self.cardinalWidth):
if self._matrix[x][y] == "infected":
# self.spread([x,y])
position = [x,y]
while position:
position = self.spread(position)
注意每个方法底部注释的变化
据我所知,这两个都应该完成同样的事情,但他们没有。一个很好用,直到我得到递归限制错误。另一个根本不起作用,但我没有得到递归错误。
为什么这些会返回不同的值?