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-9
must occur exactly once in each row. - Each of the digits
1-9
must occur exactly once in each column. - Each of the the digits
1-9
must occur exactly once in each of the 93x3
sub-boxes of the grid
Before solving this problem, it is recommended that you go through “valid sudoku” problem.
This is a classic problem of backtracking with DFS.
The solution is very simple.
We have a DFS helper function, to check if the “num” from 1 to 9 which will not conflict with already present numbers. If it is valid, then again call the helper function recursively.
To check if the number that is placed is valid or not, we use “is_valid” function.
Once all the numbers are placed, we return “true”, else of there is no solution return “false”.
Solution in C++
#include<iostream> #include<vector> using namespace std; bool isValid(vector<vector<char>>& board, int row, int col, int num) { // check row for(int i=0; i<9; i++){ if(board[i][col] == num+'0') return false; } // check row for(int j=0; j<9; j++) { if(board[row][j] == num+'0') return false; } // check block for(int i=(row/3)*3; i<(row/3)*3+3; i++) { for(int j=(col/3)*3; j<(col/3)*3+3; j++){ if(board[i][j] == num+'0') return false; } } return true; } bool help(vector<vector<char>>& board, int row, int col) { if(row == 9) return true; if(col == 9) return help(board, row+1, 0); if(board[row][col] != '.') return help(board, row, col+1); for(int num = 1; num<=9; num++) { if(isValid(board, row, col, num)) { board[row][col] = num+'0'; if(help(board, row, col+1)) return true; board[row][col] = '.'; } } return false; } void solveSudoku(vector<vector<char>>& board) { help(board, 0, 0); } int main() { vector<vector<char> > board = { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } }; solveSudoku(board); for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[0].size(); j++) { cout<< board[i][j]<<" "; } cout<<endl; } return 0; }
Output:
5 3 4 6 7 8 9 1 2 6 7 2 1 9 5 3 4 8 1 9 8 3 4 2 5 6 7 8 5 9 7 6 1 4 2 3 4 2 6 8 5 3 7 9 1 7 1 3 9 2 4 8 5 6 9 6 1 5 3 7 2 8 4 2 8 7 4 1 9 6 3 5 3 4 5 2 8 6 1 7 9