【问题标题】:On Sudoku solving关于数独求解
【发布时间】:2010-01-15 23:44:36
【问题描述】:

谁能帮我理解this solution:

 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
       }
     }
   }
 }

【问题讨论】:

  • 哪部分不明白? C代码?算法?

标签: c algorithm sudoku


【解决方案1】:

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

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

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

【讨论】:

  • 我们可以让它变慢:随机填充网格,重复直到有效。 :-)
  • @squelart mmm 猴子和莎士比亚 :)
  • 那么最快的算法是什么,我从哪里找到它?
  • @chanchal1987:快速算法会跟踪位置的“安全”值,并尝试填充允许值最少的位置(如果失败则回溯)。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 2013-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多