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.
Solution:Code:
<span style="font-size:14px;">class Solution {
public:
bool isValid(const vector<vector<char> > &board, int row, int col) {
for (int i = 0; i < 9; ++i)
if ((i != row && board[row][col] == board[i][col]) || (i != col && board[row][col] == board[row][i]))
return false;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
if (i+(row/3)*3 != row && j+(col/3)*3 != col && board[row][col] == board[i+(row/3)*3][j+(col/3)*3])
return false;
return true;
}
bool solver(vector<vector<char> > &board, int row, int col) {
if (row == 9) return true;
if (col == 9) return solver(board, row+1, 0);
for (int j = col; j < 9; ++j)
if (board[row][j] == '.') {
for (char c = '1'; c <= '9'; ++c) {
board[row][j] = c;
if (isValid(board, row, j) && solver(board, row, j+1))
return true;
board[row][j] = '.';
}
return false;
}
return solver(board, row+1, 0);
}
void solveSudoku(vector<vector<char> > &board) {
solver(board, 0, 0);
}
};</span>