TheAlgorithms-C-Plus-Plus/backtracking/sudoku_solve.cpp

92 lines
2.4 KiB
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2017-10-01 15:17:28 +08:00
using namespace std;
/// N=9;
2019-08-21 10:10:08 +08:00
int n = 9;
2017-10-01 15:17:28 +08:00
bool isPossible(int mat[][9], int i, int j, int no) {
/// Row or col nahin hona chahiye
for (int x = 0; x < n; x++) {
if (mat[x][j] == no || mat[i][x] == no) {
2017-10-01 15:17:28 +08:00
return false;
}
}
/// Subgrid mein nahi hona chahiye
2019-08-21 10:10:08 +08:00
int sx = (i / 3) * 3;
int sy = (j / 3) * 3;
for (int x = sx; x < sx + 3; x++) {
for (int y = sy; y < sy + 3; y++) {
if (mat[x][y] == no) {
2017-10-01 15:17:28 +08:00
return false;
}
}
}
return true;
}
void printMat(int mat[][9]) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
2019-08-21 10:10:08 +08:00
cout << mat[i][j] << " ";
if ((j + 1) % 3 == 0) {
2019-08-21 10:10:08 +08:00
cout << '\t';
2017-10-01 15:17:28 +08:00
}
}
if ((i + 1) % 3 == 0) {
2019-08-21 10:10:08 +08:00
cout << endl;
2017-10-01 15:17:28 +08:00
}
2019-08-21 10:10:08 +08:00
cout << endl;
2017-10-01 15:17:28 +08:00
}
}
bool solveSudoku(int mat[][9], int i, int j) {
/// Base Case
if (i == 9) {
/// Solve kr chuke hain for 9 rows already
2017-10-01 15:17:28 +08:00
printMat(mat);
return true;
}
/// Crossed the last Cell in the row
if (j == 9) {
2019-08-21 10:10:08 +08:00
return solveSudoku(mat, i + 1, 0);
2017-10-01 15:17:28 +08:00
}
/// Blue Cell - Skip
if (mat[i][j] != 0) {
2019-08-21 10:10:08 +08:00
return solveSudoku(mat, i, j + 1);
2017-10-01 15:17:28 +08:00
}
/// White Cell
/// Try to place every possible no
for (int no = 1; no <= 9; no++) {
if (isPossible(mat, i, j, no)) {
/// Place the no - assuming solution aa jayega
2017-10-01 15:17:28 +08:00
mat[i][j] = no;
2019-08-21 10:10:08 +08:00
bool aageKiSolveHui = solveSudoku(mat, i, j + 1);
if (aageKiSolveHui) {
2017-10-01 15:17:28 +08:00
return true;
}
/// Nahin solve hui
/// loop will place the next no.
2017-10-01 15:17:28 +08:00
}
}
/// Sare no try kr liey, kisi se bhi solve nahi hui
2017-10-01 15:17:28 +08:00
mat[i][j] = 0;
return false;
}
int main() {
int mat[9][9] = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0}, {0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}};
2019-08-21 10:10:08 +08:00
printMat(mat);
cout << "Solution " << endl;
solveSudoku(mat, 0, 0);
return 0;
2017-10-01 15:17:28 +08:00
}