4

有人可以帮我理解这个解决方案吗:

 Initialize 2D array with 81 empty grids (nx = 9, ny = 9)
 Fill in some empty grid with the known values
 Make an original copy of the array
 Start from top left grid (nx = 0, ny = 0), check if grid is empty
 if (grid is empty) {
   assign the empty grid with values (i)
   if (no numbers exists in same rows & same columns same as (i) & 3x3 zone (i) is currently in)
     fill in the number
   if (numbers exists in same rows & same columns same as (i) & 3x3 zone (i) is currently in)
     discard (i) and repick other values (i++)
 }
 else {
   while (nx < 9) {
     Proceed to next row grid(nx++, ny)
     if (nx equals 9) {
       reset nx = 1
       proceed to next column grid(nx,ny++)
       if (ny equals 9) {
         print solution
       }
     }
   }
 }
4

3 回答 3

14

这是一个简单的蛮力求解器。它从左上角开始,逐行从左到右工作,尝试将每个可能的数字放入每个方格,然后使用递归调用继续。失败时,它会回溯并尝试不同的选择。

调用的函数通过检查哪些值已被放置在行、列和框中safe来确定当前将值放置在某个单元格中是否合法。n

这是解决数独的最简单(也是最慢)的方法之一。

于 2010-01-15T23:48:44.530 回答
4

数独的解法有很多(不知道大家是否对它感兴趣)。它基本上是一个约束满足问题,您可以应用您最喜欢的一致性检查技术(例如 AC3)来传播约束并更早地修剪明显没有结果的路径。您的变量是每个正方形,每个变量可以采用的域是整数 1 到 9。约束是所有单元格子集上的 AllDiff。

您也可以将其表述为整数线性规划问题,让您最喜欢的 ILP 引擎(例如 lp_solve)解决它!

于 2010-01-17T05:13:26.867 回答
0

最令人困惑的是,我希望算法在完成时用正确的值填充数独矩阵,但它只是打印值然后回溯到开头,因为 t 变量的值总是写回网格(也许算法甚至设法找到另一种解决方案)。

为了在算法完成时填充网格,可以使求解函数返回真/假,然后根据内部调用的结果决定是否回溯。

于 2010-01-16T00:10:19.957 回答