LeetCode 037 Sudoku Solver

题目要求:Sudoku Solver

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.

 

分析:

参考网址:http://www.cnblogs.com/panda_lin/archive/2013/11/04/sudoku_solver.html

回溯法尝试所有解0_o

① 对于每个空位'.',遍历1~9,check合理之后递归;

② check的时候,不用遍历整个数独,只需检查加入的行、列和块就足够了。

 

代码如下:

class Solution {

public:

    bool isValidSudoku(vector<vector<char> > &board, int x, int y) {

        int row, col;

        

        // Same value in the same column?

        for (row = 0; row < 9; ++row) {

            if ((x != row) && (board[row][y] == board[x][y])) {

                return false;

            }

        }

        

        // Same value in the same row?

        for (col = 0; col < 9; ++col) {

            if ((y != col) && (board[x][col] == board[x][y])) {

                return false;

            }

        }

        

        // Same value in the 3 * 3 block it belong to?

        for (row = (x / 3) * 3; row < (x / 3 + 1) * 3; ++row) {

            for (col = (y / 3) * 3; col < (y / 3 + 1) * 3; ++col) {

                if ((x != row) && (y != col) && (board[row][col] == board[x][y])) {

                    return false;

                }

            }

        }

        

        return true;

    }

    

    bool internalSolveSudoku(vector<vector<char> > &board) {

        for (int row = 0; row < 9; ++row) {

            for (int col = 0; col < 9; ++col) {

                if ('.' == board[row][col]) {

                    for (int i = 1; i <= 9; ++i) {

                        board[row][col] = '0' + i;

                        

                        if (isValidSudoku(board, row, col)) {

                            if (internalSolveSudoku(board)) {

                                return true;

                            }

                        }

                        

                        board[row][col] = '.';

                    }

                    

                    return false;

                }

            }

        }

        

        return true;

    }

    

    void solveSudoku(vector<vector<char> > &board) {

        internalSolveSudoku(board);

    }

};

 

你可能感兴趣的:(LeetCode)