-
Notifications
You must be signed in to change notification settings - Fork 0
/
A-Soduku_Game.cpp
132 lines (118 loc) · 2.4 KB
/
A-Soduku_Game.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
#include <bits/stdc++.h>
using namespace std;
// Ashfak Hossain Evan, CSE, American International University-Bangladesh (AIUB)
const int N = 9;
bool findEmptyLocation(int board[N][N], int &r, int &cl)
{
for (r = 0; r < N; r++)
{
for (cl = 0; cl < N; cl++)
{
if (board[r][cl] == 0)
{
return true;
}
}
}
return false;
}
bool isRowValid(int board[N][N], int r, int num)
{
for (int cl = 0; cl < N; cl++)
{
if (board[r][cl] == num)
{
return false;
}
}
return true;
}
bool isColValid(int board[N][N], int cl, int num)
{
for (int r = 0; r < N; r++)
{
if (board[r][cl] == num)
{
return false;
}
}
return true;
}
bool isBoxValid(int board[N][N], int boxStartRow, int boxStartCol, int num)
{
for (int r = 0; r < 3; r++)
{
for (int cl = 0; cl < 3; cl++)
{
if (board[r + boxStartRow][cl + boxStartCol] == num)
{
return false;
}
}
}
return true;
}
bool isNumValid(int board[N][N], int r, int cl, int num)
{
return isRowValid(board, r, num) && isColValid(board, cl, num) && isBoxValid(board, r - r % 3, cl - cl % 3, num);
}
bool solveSudoku(int board[N][N])
{
int r, cl;
if (!findEmptyLocation(board, r, cl))
{
return true;
}
for (int num = 1; num <= 9; num++)
{
if (isNumValid(board, r, cl, num))
{
board[r][cl] = num;
if (solveSudoku(board))
{
return true;
}
board[r][cl] = 0;
}
}
return false;
}
void printBoard(int board[N][N])
{
for (int r = 0; r < N; r++)
{
for (int cl = 0; cl < N; cl++)
{
cout << board[r][cl];
}
cout << endl;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL), cout.tie(NULL);
// Code Start From Here
int board[N][N];
for (int r = 0; r < N; r++)
{
for (int cl = 0; cl < N; cl++)
{
char c;
cin >> c;
if (c == '.')
{
board[r][cl] = 0;
}
else
{
board[r][cl] = c - '0';
}
}
}
if (solveSudoku(board))
{
printBoard(board);
}
return 0;
}