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

class Solution {
private:
    bool isValidSudoku(vector<vector<char>> & board, int row, int col,
            char val) {
        int N = board.size();

        for (int i = 0; i < N; i++) {
            if (board[row][i] == val)
                return false;
        }

        for (int i = 0; i < N; i++) {
            if (board[i][col] == val)
                return false;
        }

        int r = row / 3 * 3;
        int c = col / 3 * 3;
        for (int i = r; i < r + 3; i++) {
            for (int j = c; j < c + 3; j++) {
                if (board[i][j] == val)
                    return false;
            }
        }
        return true;
    }
    bool solveSudoku(vector<vector<char>>& board, int row, int col) {

        int N = board.size();
        if (row == N) return true;
        if (col == N) return solveSudoku(board, row + 1, 0);
        if (board[row][col] != '.')
            return solveSudoku(board, row, col + 1);

        for (char k = '1'; k <= '9'; k++) {
            if (!isValidSudoku(board, row, col, k))
                continue;
            board[row][col] = k;
            if(solveSudoku(board, row, col + 1))
                return true;
            board[row][col] = '.';
        }
        return false;
    }

public:
    void solveSudoku(vector<vector<char>>& board) {
        solveSudoku(board, 0, 0);
    }
};

 

posted @ 2016-11-04 16:13  wxquare  阅读(185)  评论(0编辑  收藏  举报