forked from RushikeshRathod/Soduku
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Brute force algorithm.cpp
171 lines (152 loc) · 3.61 KB
/
Brute force algorithm.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class sudoku
{
int arr[10][10];
public: void Input()
{
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
cin>>arr[i][j];
}
}
}
public: void Display()
{
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
cout<<arr[i][j]<<" ";
if((j+1)%3==0)
{
cout<<" ";
}
}
cout<<endl;
if((i+1)%3==0)
{
cout<<endl;
}
}
}
public: int Safetoaddinrow(int n, int r)
{
int temp;
int flag=1;
for(int i=0;i<9;i++)
{
temp=arr[r][i];
if(temp==n)
flag=flag*0;
}
if(flag==0)
return 0;
else
return 1;
}
public: int Safetoaddincolumn(int n, int c)
{
int temp;
int flag=1;
for(int i=0;i<9;i++)
{
temp=arr[i][c];
if(temp==n)
flag=flag*0;
}
if(flag==0)
return 0;
else
return 1;
}
public: int Safetoaddinsubmatrix(int n, int startx, int starty)
{
int temp;
int flag=1;
for(int i=startx;i<startx+3;i++)
{
for(int j=starty;j<starty+3;j++)
{
temp=arr[i][j];
if(temp==n)
{
flag=flag*0;
}
}
}
if(flag==0)
return 0;
else
return 1;
}
public: int Check(int k,int i, int j)
{
int p=Safetoaddinrow(k,i);
int q=Safetoaddincolumn(k,j);
int r=i/3;
int s=j/3;
r=r*3;
s=s*3;
int t=Safetoaddinsubmatrix(k,r,s);
int val=p*q*t;
return val;
}
public: void Solve()
{
for(int i=0;i<9;i++)
{
for( int j=0;j<9;j++)
{
if(arr[i][j]==0)
{
int flag=0;
for(int k=1;k<=9;k++)
{
int temp=Check(k,i,j);
if(temp==1)
{
flag=flag+1;
}
}
if(flag==1)
{
for(int k=1;k<=9;k++)
{
int temp=Check(k,i,j);
if(temp==1)
arr[i][j]=k;
}
}
}
}
}
int indicator=1;
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
if(arr[i][j]==0)
{
indicator=indicator*0;
}
}
}
if(indicator==0)
{
Solve();
}
}
};
int main() {
sudoku s1;
s1.Input();
s1.Solve();
s1.Display();
}