-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathSolve-Sudoku.cpp
108 lines (81 loc) · 2.03 KB
/
Solve-Sudoku.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int n = 9;
/*
given a valid input for sudoku problem like one in the newspapers, it solves and returns a valid answer
*/
bool check(vector<vector<int>> &board, int row, int col, int key){
for(int j1=0;j1<n;j1++){ //checking in row
if(board[row][j1]==key) return 0;
}
for(int j1=0;j1<n;j1++){ //checking in col
if(board[j1][col]==key) return 0;
}
int x0 = (row/3); //checking in small box
x0 *= 3;
int x1 = col/3;
x1 *= 3;
for(int i1=x0;i1<x0+3;i1++){
for(int j1=x1;j1<x1+3;j1++){
if(board[i1][j1]==key) return 0;
}
}
return 1;
}
void printt(vector<vector<int>> &board){
for(int i = 0; i<9;i++){
for(int j =0;j<n;j++){
cout<<board[i][j]<<" ";
}
cout<<endl;
}
}
bool checksudoku(vector<vector<int>> &board){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]==0) return 0;
}
}
return 1;
}
void sudoku(vector<vector<int>> &board, int row, int col){
if(row == 9){
printt(board);
return;
}
int nr,nc;
if(col==8){
nr=row+1;
nc=0;
}
else{
nr=row; nc = col+1;
}
if(board[row][col]!=0){
sudoku(board,nr,nc);
}
else{
for(int i = 1;i<=9;i++){
if(board[row][col]==0 && check(board,row,col,i)==1){
board[row][col] = i;
sudoku(board,nr,nc);
board[row][col]=0;
}
}
}
}
int main() {
int n, m;
n=9,m=9;
vector < vector < int >> arr(n, vector < int > (m));
vector < vector < int >> visited(n, vector < int > (m));
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
cin >> arr[i][j];
if(arr[i][j]) visited[i][j]=1;
}
}
sudoku(arr,0,0);
return 0;
}