leetcde37. Sudoku Solver

时间:2023-03-09 18:50:39
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.

leetcde37. Sudoku Solver

A sudoku puzzle...

leetcde37. Sudoku Solver

...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 = ; i < N; i++) {
if (board[row][i] == val)
return false;
} for (int i = ; i < N; i++) {
if (board[i][col] == val)
return false;
} int r = row / * ;
int c = col / * ;
for (int i = r; i < r + ; i++) {
for (int j = c; j < c + ; 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 + , );
if (board[row][col] != '.')
return solveSudoku(board, row, col + ); for (char k = ''; k <= ''; k++) {
if (!isValidSudoku(board, row, col, k))
continue;
board[row][col] = k;
if(solveSudoku(board, row, col + ))
return true;
board[row][col] = '.';
}
return false;
} public:
void solveSudoku(vector<vector<char>>& board) {
solveSudoku(board, , );
}
};