Sudoku Solver, Now it's possible to solve expert level question in less than 2 minutes

来源:互联网 发布:ccleaner清除电脑数据 编辑:程序博客网 时间:2024/06/05 19:13

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

Interesting to me is that, I have been playing Sudoku for a while (maybe 5 years), this game would always reminds me the happy time back to 4 years ago in Chicago, every morning I would pick a pack of ChicagoRedEye to read, simply because it's free for everyone. And there might be a board of Sudoku and one word puzzle for people to have fun. As a non-native lazy man, it's quite difficult to solve the word-puzzle, but I could always solve the Dudoku in minutes, sometimes the Sudoku would be very difficult, thus I have to make a copy and try to solve it again ==!.

After I had smartphone, Sudoku became my partner to kill boring time, :) especially when waiting for bus or plane. But, it's only recently did I realized that I should write a program to solve the problem on LeetCode OJ. 

Preconditions to solve Sudoku:
1st, what does a valid cell mean?
 a valid cell means there's no duplication character in the same row and the same column; and also no duplication in the same 3*3 small board.

2nd, how to locate the small board?
There are 9 start coordinates could be considered as the 'start point' for each small board: (0,0), (0, 3), (0, 6)-----(6,6);
So, to a certain coordinate (x, y), we can use x/3*3 and y/3*3 to get the start point. the use two for loops to check if there's any duplicatio in the same small 3*3 board.
3rd, how to translate between 'char' and 'int'?
Actually, here we do not need to translate between Integer and Characters, even when we are doing for(i=1; i<=9; i++) loop, we can simply use for(char letter='1'; letter<='9'; letter++) loop, but one tricky thing is that, this kind of for loop DOES DOES not work beyond '9'. :)

4th, any equation or logical method?
Nope, I just used Permutation, that's how computer works. 

/*****************************Below, is my solution to Sudoku*****************************************/

GITHUB: https://github.com/breezedu/LeetCode2012/blob/master/SudokuSolve.java


/**********
* create a stack to store all index of empty cells, index = row*9+col;
* call permulateFill() method to fill the board[][];
* @param board
*/

/***************
* recovery index into [row, col];
* try every possible letter from '0' to '9', to see if that letter is a valid option for that
* cell 'currently', if yes, update board[row][col] to be that valid letter, then call permulateFill()
* to check next empty cell from emptyCells stack;

*/

And here is the Eclipse out print:


0 0
原创粉丝点击