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.
A sudoku puzzle...
...and its solution numbers marked in red.
My Iterative BP Code
class Solution {
public:
bool checkCell(vector<vector<char> >& board, int row, int col, char c)
{
for (int i = 0; i < 9; i++)
{
if (board[row][i] == c)
return false;
if (board[i][col] == c)
return false;
if (board[row-row%3+i/3][col-col%3+i%3] == c)
return false;
}
return true;
}
void solveSudoku(vector<vector<char> >& board) {
vector<int> indices;
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
if (board[i][j] == '.')
indices.push_back(9*i+j);
int size = indices.size();
int i = 0;
while (i < size)
{
int idx = indices[i];
int row = idx / 9;
int col = idx % 9;
char c;
if (board[row][col] == '.')
c = '1';
else
c = board[row][col] + 1;
for (; c < '9' + 1; c++)
{
// Check
if (checkCell(board, row, col, c) == false)
continue;
board[row][col] = c;
break;
}
if (c < '9' + 1)
{
i++;
}
else // Backtrack
{
board[row][col] = '.';
i--;
}
}
}
};
Runtime: 48 ms
My Recursive BP Code
class Solution {
public:
bool checkCell(vector<vector<char> >& board, int row, int col, char c)
{
for (int i = 0; i < 9; i++)
{
if (board[row][i] == c)
return false;
if (board[i][col] == c)
return false;
if (board[row-row%3+i/3][col-col%3+i%3] == c)
return false;
}
return true;
}
bool doSolveSudoku(vector<vector<char> >& board, int row, int col)
{
if (row == 9)
return true;
if (col == 9)
return doSolveSudoku(board, row + 1, 0);
if (board[row][col] != '.')
return doSolveSudoku(board, row, col + 1);
for (char c = '1'; c <= '9'; c++)
{
if (checkCell(board, row, col, c))
{
board[row][col] = c;
if (doSolveSudoku(board, row, col + 1))
return true;
board[row][col] = '.';
}
}
return false;
}
void solveSudoku(vector<vector<char> >& board) {
doSolveSudoku(board, 0, 0);
}
};
Runtime: 49 ms