
sudoko = {{8, 0, 0, 0, 0, 0, 0, 0, 0},{0, 0, 3, 6, 0, 0, 0, 0, 0},{0, 7, 0, 0, 9, 0, 2, 0, 0},{0, 5, 0, 0, 0, 7, 0, 0, 0},{0, 0, 0, 0, 4, 5, 7, 0, 0},{0, 0, 0, 1, 0, 0, 0, 3, 0},{0, 0, 1, 0, 0, 0, 0, 6, 8},{0, 0, 8, 5, 0, 0, 0, 1, 0},{0, 9, 0, 0, 0, 0, 4, 0, 0}};function check(row, line,number,matrix)--判断该行该列是否有重复数字for i = 1 ,9 doif matrix[row][i] == number or matrix[i][line] == number thenreturn falseendend--判断小九宫格是否有重复local tempRow = math.ceil (row / 3) - 1local tempLine =math.ceil (line/ 3) - 1for i = 1,3 dofor j = 1,3 doif (matrix[tempRow * 3 + i][tempLine * 3 + j] == number) thenreturn falseendendendreturn trueendfunction printArray(matrix)for k,v in ipairs(matrix) doprint(table.concat(v,","))endendfunction backTrace(i,j,matrix)--结尾if i == 9 and j == 10 thenprintArray(matrix)returnend--到达列尾if j == 10 thenj = 1i = i +1endif (matrix[i][j] == 0) thenfor k = 1 ,9 doif check(i, j, k,matrix) thenmatrix[i][j] = kbackTrace(i, j + 1,matrix)--回溯还原matrix[i][j] = 0;endendelse--下个位置backTrace(i, j + 1,matrix);endendbackTrace(1,1,sudoko)
--优化版本sudoko = {}--初始化sudoko.matrix = {{8, 0, 0, 0, 0, 0, 0, 0, 0},{0, 0, 3, 6, 0, 0, 0, 0, 0},{0, 7, 0, 0, 9, 0, 2, 0, 0},{0, 5, 0, 0, 0, 7, 0, 0, 0},{0, 0, 0, 0, 4, 5, 7, 0, 0},{0, 0, 0, 1, 0, 0, 0, 3, 0},{0, 0, 1, 0, 0, 0, 0, 6, 8},{0, 0, 8, 5, 0, 0, 0, 1, 0},{0, 9, 0, 0, 0, 0, 4, 0, 0}};sudoko.count = 0function sudoko:check(row, line,number)local matrix = self.matrix--判断该行该列是否有重复数字for i = 1 ,9 doif matrix[row][i] == number or matrix[i][line] == number thenreturn falseendend--判断小九宫格是否有重复local tempRow = math.ceil (row / 3) - 1local tempLine =math.ceil (line/ 3) - 1for i = 1,3 dofor j = 1,3 doif (matrix[tempRow * 3 + i][tempLine * 3 + j] == number) thenreturn falseendendendreturn trueendfunction sudoko:printArray()local matrix = self.matrixfor k,v in ipairs(matrix) doprint(table.concat(v,","))endprint("统计backTrace调用次数:" .. self.count)endfunction sudoko:backTrace(i,j)local matrix = self.matrix--统计函数调用次数self.count = self.count + 1--结尾if i >= 9 and j >= 10 thenself:printArray()return trueend--到达列尾if j == 10 theni = i +1j = 1endif (matrix[i][j] == 0) thenfor k = 1 ,9 doif self:check(i, j, k) thenmatrix[i][j] = kif self:backTrace(i, j + 1) thenreturn trueend--回溯还原matrix[i][j] = 0;endendelse--下个位置return self:backTrace(i, j + 1);endendsudoko:backTrace(1,1)
优化之后backTrace函数调用次数72097次,之前3031697次
参考
http://blog.csdn.net/tianyaleixiaowu/article/details/50912924
