Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- // to check if the row already has the number
- bool checkRow(int r, int k, vector<vector<int> > &v){
- for(int i : v[r]){
- if(i == k){
- return false;
- }
- }
- return true;
- }
- // to check if the column already has the number
- bool checkColumn(int c, int k, vector<vector<int> > &v){
- for(int i = 0; i < v.size(); i++){
- if(v[i][c] == k){
- return false;
- }
- }
- return true;
- }
- // to check if the submatrix already has the number
- bool checkSubmatrix(int r, int c, int k, vector<vector<int> > &v){
- // calculate column range
- int colInterval = ceil((c + 1) / 3.0);
- int rowInterval = ceil((r + 1) / 3.0);
- for(int i = 3 * (rowInterval - 1); i < 3 * rowInterval; i++){
- for(int j = 3 * (colInterval - 1); j < 3 * colInterval; j++){
- if(v[i][j] == k){
- return false;
- }
- }
- }
- return true;
- }
- // main solve function
- void solveSudoko(int r, int c, vector<vector<int> > &v){
- if(c >= 9){
- r = r + 1;
- c = 0;
- }
- if(r >= 9){
- for(int i = 0; i < 9; i++){
- cout << '\n';
- for(int j = 0; j < 9; j++){
- cout << v[i][j] << ' ';
- }
- }
- cout << '\n' << '\n';
- return;
- }
- if(v[r][c] == 0){
- for(int k = 1; k < 10; k++){
- bool isSafe = checkRow(r, k, v) && checkColumn(c, k, v) && checkSubmatrix(r, c, k, v);
- if(isSafe){
- v[r][c] = k;
- solveSudoko(r, c + 1, v);
- v[r][c] = pas0;
- }
- }
- }
- else{
- solveSudoko(r, c + 1, v);
- }
- }
- int main() {
- // your code goes here
- vector<vector<int> > v(9, vector<int>(9, 0));
- for(int i = 0; i < 9; i++){
- for(int j = 0; j < 9; j++){
- cin >> v[i][j];
- }
- }
- solveSudoko(0, 0, v);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement