LeetCode 37. Sudoku Solver

/*
<p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p><p>Empty cells are indicated by the character <code>'.'</code>.</p><p>You may assume that there will be only one unique solution.</p>
*/

class Solution {
private:
bool checkValid(vector<vector<char>> board, int i, int j) {
    bool flags[9] = {0};
    for(int x = 0; x < 9; ++x) {
        if(board[i][x] >= '1' && board[i][x] <= '9') {
            if(!flags[board[i][x] - '1']) flags[board[i][x] - '1'] = true;
            else return false;
        }
    }
    memset(flags, 0 , 9);
    for(int x = 0; x < 9; ++x) {
        if(board[x][j] >= '1' && board[x][j] <= '9') {
            if(!flags[board[x][j] - '1']) flags[board[x][j] - '1'] = true;
            else return false;
        }
    }
    memset(flags, 0, 9);
    int xx = i / 3 * 3;
    int yy = j / 3 * 3;
    for(int x = 0; x < 3; ++x) {
        for(int y = 0; y < 3; ++y) {
            if(board[xx + x][yy + y] >= '1' && board[xx + x][yy + y] <= '9') {
                if(!flags[board[xx + x][yy + y] - '1']) flags[board[xx + x][yy + y] - '1'] = true;
                else return false;
            }
        }
    }
    return true;
}
public:
    bool solveSudoku(vector<vector<char>>& board) {
        int m = board.size();
        int n = board[0].size();
        if(n != m) return false;
        for(int i = 0; i < n; ++i) {
            for(int j = 0; j < n; ++j) {
                if(board[i][j] != '.')
                    continue;
                for(char a = '1'; a <= '9'; ++a) {
                    board[i][j] = a;    // place the number
                    if(checkValid(board, i, j)) {
                        if(solveSudoku(board)) return true;
                    }
                    board[i][j] = '.';   // if it is not good, reverse it back.
                }
                return false;
            }
        }
        return true;
    }
};

你可能感兴趣的:(LeetCode 37. Sudoku Solver)