37. Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits
1-9must occur exactly once in each row.Each of the digits
1-9must occur exactly once in each column.Each of the the digits
1-9must occur exactly once in each of the 93x3sub-boxes of the grid.
Empty cells are indicated by the character '.'.
A sudoku puzzle...
...and its solution numbers marked in red.
Note:
The given board contain only digits
1-9and the character'.'.You may assume that the given Sudoku puzzle will have a single unique solution.
The given board size is always
9x9.
bool isValid(vector<vector<char> >& board, int r, int c) {
for (int i = 0; i < 9; ++i) {
// row check
if (i != c && board[r][i] == board[r][c]) return false;
// col check
if (i != r && board[i][c] == board[r][c]) return false;
// 3x3 box check
int boxRow = 3 * (r / 3) + (i / 3), boxCol = 3 * (c / 3) + (i % 3);
if ((boxRow != r || boxCol != c) && board[boxRow][boxCol] == board[r][c]) return false;
}
return true;
}
bool helper(vector<vector<char> >& board, int i, int j) {
if (i == 9) return true;
if (j == 9) return helper(board, i + 1, 0);
if (board[i][j] == '.') {
for (char c = '1'; c <= '9'; ++c) {
board[i][j] = c;
if (isValid(board, i, j) && helper(board, i, j + 1)) return true;
board[i][j] = '.';
}
} else {
return helper(board, i, j + 1);
}
return false;
}
void solveSudoku(vector<vector<char>>& board) { // time: O(9^(# of empty slots)); space: O(# of empty slots)
if (board.size() != 9 || board[0].size() != 9) return;
helper(board, 0, 0);
}Last updated
Was this helpful?