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.

本题是求解数独,采用回溯的算法,依次寻找。时间:92ms。代码如下:

class Solution {
public:
    bool isValid(vector<vector<char>>& board, size_t i, size_t j){
        for (size_t x = 0; x < 9; ++x){
            if (board[x][j] == board[i][j] && x != i)
                return false;
        }
        for (size_t y = 0; y < 9; ++y){
            if (board[i][y] == board[i][j] && y != j)
                return false;
        }
        for (size_t x = 3 * (i / 3); x < 3 * (i / 3) + 3; ++x){
            for (size_t y = 3 * (j / 3); y < 3 * (j / 3) + 3; ++y){
                if (board[x][y] == board[i][j] && x != i && y != j)
                    return false;
            }
        }
        return true;
    }
    bool makeSolveSudoku(vector<vector<char>>& board) {
        for (size_t i = 0; i < 9; ++i){
            for (size_t j = 0; j < 9; ++j){
                if (board[i][j] == '.'){
                    for (int k = 1; k <= 9; ++k){
                        board[i][j] = k + '0';
                        if (isValid(board, i, j) && makeSolveSudoku(board))
                            return true;
                        board[i][j] = '.';
                    }
                    return false;
                }
            }
        }
        return true;
    }
    void solveSudoku(vector<vector<char>>& board) {
        makeSolveSudoku(board);
    }
};

 

posted on 2015-06-16 10:28  NealCaffrey989  阅读(120)  评论(0编辑  收藏  举报