LeetCode 37.解数独

class Solution {
public:
    void solveSudoku(vector>& board) {
        vector>ans;
        backtraking(board);
    }
    bool isValid(vector>board, int row, int col,int x) {
        for (int i = 0; i < 9; i++)
            if (board[row][i] - '0' == x)
                return false;
        for (int i = 0; i < 9; i++)
            if (board[i][col] - '0' == x)
                return false;
        int startRow = (row / 3) * 3, startCol = (col / 3) * 3;
        for (int i = startRow; i < startRow + 3; i++) {
            for (int j = startCol; j < startCol + 3; j++) {
                if (board[i][j] - '0' == x)
                    return false;
            }
        }
        return true;
    }
    bool backtraking(vector>& board) {
        for (int i = 0; i < board.size(); i++) {
            for (int j = 0; j < board[0].size(); j++) {
                if (board[i][j] != '.')
                    continue;
                for (int x = 1; x <= 9; x++) {
                    if (isValid(board, i, j, x)) {
                        board[i][j] = '0' + x;
                        if (backtraking(board))return true;
                        board[i][j] = '.';
                    }
                }
                return false;
            }
        }
        return true;
    }
};

你可能感兴趣的:(算法,c++,leetcode)