【leetcode】 Sudoku Solver

来源:互联网 发布:suse linux 设置网关 编辑:程序博客网 时间:2024/06/06 09:56

问题:

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.

说明:

  • 数独有三个要求:1)每一行的元素都在1-9之间,且同一行内,每一位的数字不重复。2)列与行的要求一致 。3)整个数独的9*9方格,是由9个3*3的9宫格组成的,要求每个九宫格内的数组在1-9之间,且不重复。
  • 程序给定的数独格子中,待填写的部分用‘.’ 来表示,“已经填入的数作为填数判断的提示,称为提示数”(摘自百度百科)。并且默认给定的提示数是正确的,就是说,在此基础上是有解存在的。更多的关于数独的知识,还可以参考<<编程之美>>,里面有讲解。
  • 只需找到一个合法的解即可。

分析:

如果不考虑优化,这个问题就可以对每个尚未填写的位置进行试探,从1-9,然后用上面列举的3个条件去卡,如果满足,就递归进行,如果不行,就把当前填写的试探值抹去(重新复位为‘。)

实现:

bool isValid(vector<vector<char> > &board, int px, int py) {int len = board.size();//check rows and cols.for (int i = 0; i < len; ++i){if(i != py && board[px][i] == board[px][py] ||i != px && board[i][py] == board[px][py])return false;}//check boxint basex = px/3 * 3;int basey = py/3 * 3;for (int i = 0; i < 3; ++i)for (int j = 0; j < 3; ++j){if( basex + i != px && basey + j != py &&board[basex + i][basey + j] == board[px][py])return false;}return true;}bool currentSudoku(vector<vector<char> > &board) {for (int row = 0; row < 9; ++row)for (int col = 0; col < 9; ++col){if(board[row][col] == '.'){    for(char num = '1'; num <= '9'; ++num)        {board[row][col] = num;        if(isValid(board, row, col) && currentSudoku(board))            return true;board[row][col] = '.';        }    return false;//no number can add in this point.}}return true;}void solveSudoku(vector<vector<char> > &board) {currentSudoku(board);}


0 0
原创粉丝点击