π One-stop destination for all your technical interview Preparation π
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Solve function algorithm:
if current cell is already marked, move to the next cell.
isValid function algorithm:
int iindex = newRow + i, jindex = newCol + j;`class Solution {
private:
bool isValid(vector<vector<char>>& board, int row, int col, char c)
{
// row check
for (int i = 0; i < 9; i++)
if (board[i][col] == c)
return false;
// col check
for (int i = 0; i < 9; i++)
if (board[row][i] == c)
return false;
// box check
int newRow = (row / 3) * 3, newCol = (col / 3) * 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[newRow + i][newCol + j] == c)
return false;
}
}
return true;
}
bool solve(vector<vector<char>>& board, int row, int col)
{
// done
if (row == 9) return true;
// time for next row
if (col == 9) return solve(board, row + 1, 0);
// already marked
if (board[row][col] != '.') return solve(board, row, col + 1);
for (char c = '1'; c <= '9'; c++) {
if (isValid(board, row, col, c)) {
board[row][col] = c;
// without return here, the board reverts to initial state
if (solve(board, row, col + 1))
return true;
board[row][col] = '.';
}
}
return false;
}
public:
void solveSudoku(vector<vector<char>>& board)
{
solve(board, 0, 0);
}
};
class Solution {
private:
bool isValid(vector<vector<char>>& board, int row, int col, int num)
{
for (int i = 0; i < 9; i++) {
if (board[row][i] == num)
return false;
if (board[i][col] == num)
return false;
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == num)
return false;
}
return true;
}
bool solve(vector<vector<char>>& board)
{
int n = board.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == '.') { // empty cell
for (char k = '1'; k <= '9'; k++) { // try 1 to 9 characters
if (isValid(board, i, j, k)) {
board[i][j] = k;
if (solve(board)) {
return true;
} else {
board[i][j] = '.';
}
}
}
// can't fit any number
return false;
}
}
}
// all cells are filled
return true;
}
public:
void solveSudoku(vector<vector<char>>& board)
{
solve(board);
}
};