【发布时间】:2014-02-02 18:55:20
【问题描述】:
我知道return语句会使执行跳出函数。因此,我对以下递归解决 Suduko 难题的程序感到担忧:
class Puzzle:
def __init__(self):
self.loop = 0
self.answer = 0
self.done = False
def same_row(self,i,j):
return i/9 == j/9
def same_col(self,i,j):
return (i-j)%9 == 0
def same_block(self,i,j):
return (i/27 == j/27 and i%9/3 == j%9/3)
def print_format(self,a):
for row in range(9):
for col in range(9):
print '%s ' % a[9*row + col],
print ''
def solve(self,a):
self.loop += 1
if self.answer == 1 and self.loop>100000 or self.answer == 2:
self.done = True
i = a.find('0')
if i == -1:
self.answer += 1
print 'after %d loops worked out solution %d:' % (self.loop, self.answer)
self.print_format(a)
return
excluded_num = set()
for j in range(81):
if self.same_row(i,j) or self.same_col(i,j) or self.same_block(i,j):
excluded_num.add(a[j])
for m in '123456789':
if m not in excluded_num:
if self.done:
return
print 'xxx loop %d' % self.loop
self.solve(a[:i]+m+a[i+1:])
if __name__ == '__main__':
puz = Puzzle()
sudoku="060593000901000500030400090108020004400309001200010609080006020004000807000000000"
puz.solve(sudoku)
这是一个解决数独难题的程序,我检查输出我发现一个我不明白为什么的问题,输出是这样的:
谁能告诉我为什么要打印'xxx loop 125'和'xxx loop 175'?由于第 32 行有 return 语句,为什么执行仍然失败并打印出来?非常感谢
【问题讨论】:
-
在放置该语句时变得更加困惑:xxx 循环 174 在 175 个循环后得出解决方案 2:7 6 2 5 9 3 1 4 8 9 4 1 2 7 8 5 3 6 8 3 5 4 6 1 7 9 2 1 9 8 6 2 5 3 7 4 4 7 6 3 8 9 2 5 1 2 5 3 7 1 4 6 8 9 5 8 7 1 4 6 9 2 3 3 1 4 9 5 2 8 6 7 6 2 9 8 3 7 4 1 5 xxx 循环 175 内循环 176 内循环 176 内循环 176 内循环 176 内循环 176 内循环 176 内循环 176 内循环 176 内循环 176 内循环 176 内循环 176