A Fast Sudoku Solver: LeetCode Problem

This is an efficient and fast solver for Sudoku problem.  I passed the large test within 24ms.  


The problem is below:

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

A sudoku puzzle...


...and its solution numbers marked in red.

The basic idea is to use depth first search and backtrack.  To do efficient depth first search, I did not use recursion, but used a loop.  To do efficient backtrack, we need a method to recover the original state.  But how?


The idea is below:

if in (i, j), we put a number x (1~9), then we will set 

rows[i][x-1] = cols[j][x-1] = squares[i/3*3 + j/3][x-1] = 1;


and we remember what number we put in (i, j)


when we recover the original state, we unset rows, cols, squares by

rows[i][x-1] = cols[j][x-1] = squares[i/3*3 + j/3][x-1] = 0;


In addition, when we are traversing the search tree, we need to know if this is the first time we visit this node.  If it is the first time, we need to try (1~9).  If it is not, and the last time the number we tried to put there is x, we need to try (x+1 ~ 9)


  

有一些文章中提到了使用DLX (dynamic links)来解决数独问题。DLX的精华在于在backtracking中能够快速的恢复原有的状态。但是对于数独问题,使用DLX明显过于复杂。而是否能够用另外一中方法达到DLX的核心思想呢?


我们可以用三个二维数组来记录每一行,列,方块,里面已经填了的数,每次尝试放一个新的数的时候,把改行,列,方块上的对应位set成1,如果要backtrack的话,把该bit unset成0


在dfs中,要区分是否是第一次到达search tree的node


一个search tree的例子:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值