Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <cmath>
- #include <algorithm>
- #include <string>
- #include <set>
- using namespace std;
- int b[9][9];//the sudoku grid
- set<int >rows[9];//to know which numbers appears in each row
- set<int >columns[9];//to know which numbers appears in each column
- set<int >blocks[9];//to know which numbers appears in each 3*3 block
- int itr=0;//to count how many iterations have been made
- int getBlock(int i,int j){//to get the block number by the row and column index
- if(i<3){
- if(j<3)return 0;
- else if(j<6)return 1;
- else return 2;
- }else if(i<6){
- if(j<3)return 3;
- else if(j<6)return 4;
- else return 5;
- }else{
- if(j<3)return 6;
- else if(j<6)return 7;
- else return 8;
- }
- }
- bool solve(int i,int j){
- //to print the number of iterations made
- itr++;
- if(itr%100000==0)cout<<itr<<endl;
- if(j==9){//to move to the next row
- j=0;
- i++;
- }
- if(i==9)return true;//which means we have finished the grid
- if(b[i][j]!=0)return solve(i,j+1);//if the cell isn't empty move to the next cell
- for(int v=1;v<=9;v++){//try every possible number 1->9
- if(rows[i].count(v)>0 || columns[j].count(v)>0 || blocks[getBlock(i, j)].count(v)>0)//continue if the numbers appears in the same row, column or block
- continue;
- b[i][j]=v;//try the number
- rows[i].insert(v);//put the number in the ith row
- columns[j].insert(v);//put the number in the jth row
- blocks[getBlock(i, j)].insert(v);//put the number in the correct block
- bool tr=solve(i,j+1);//try to move to the next cell with this number
- if(tr)return tr;//means that we have reached the last cell and returned true
- //if we did't return true
- //erase the number from the row ,column and block
- rows[i].erase(v);
- columns[j].erase(v);
- blocks[getBlock(i, j)].erase(v);
- //try next number
- }
- //we did't find any suitable number so return false
- b[i][j]=0;
- return false;
- }
- int main() {
- cin.tie(0);
- cin.sync_with_stdio(0);
- //read the numbers
- for(int i=0;i<9;i++){
- for(int j=0;j<9;j++){
- cin>>b[i][j];
- rows[i].insert(b[i][j]);
- columns[j].insert(b[i][j]);
- blocks[getBlock(i,j)].insert(b[i][j]);
- }
- }
- //solve it from first cell
- bool s=solve(0,0);
- if(s){//means we found an valid solution
- for(int i=0;i<9;i++){
- for(int j=0;j<9;j++){
- string sep=" ";
- if(j%3==2)sep=" | ";
- cout<<b[i][j]<<sep;
- }
- cout<<endl;
- if(i%3==2)cout<<"____________________\n";
- }
- }
- else{//sadly we did't find a solution
- cout<<":(";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement