【leetCode】37_解数独

和8皇后完全一样。

class Solution {
public:
    void solveSudoku(vector>& board) {
        dfs(board);
    }
    
    bool dfs(vector>& board){
        for (int i = 0; i < 9; i ++){
            for (int j = 0; j < 9; j ++){
                if (board[i][j] == '.'){
                    for (int v = 1; v < 10; v ++){
                        if (checkSudoku(board, i, j, v)){
                            board[i][j] = '0' + v;
                            if (dfs(board))
                                return true;
                            board[i][j] = '.';
                        }
                    }
                    return false;
                }
            }
        }
        return true;
    }
    
    bool checkSudoku(vector>& board, int x, int y, int value){
        for (int i = 0; i < 9; i ++){
            if (board[x][i] - '0' == value || board[i][y] - '0' == value)
                return false;
        }
        int x_min = x / 3 * 3, y_min = y / 3 * 3, x_max = x_min + 3, y_max = y_min + 3;
        for (int i = x_min; i < x_max; i ++){
            for (int j = y_min; j < y_max; j ++){
                if (board[i][j] - '0' == value)
                    return false;
            }
        }
        return true;
    }
};

 

你可能感兴趣的:(leetCode)