Skip to content

Commit 730779d

Browse files
authored
Merge pull request #557 from MrLakshay/patch-1
Adding sudoku solver
2 parents e18a609 + 354ae33 commit 730779d

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed

C++/Sudoku.cpp

+91
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/*
2+
Author : Lakshay Goel
3+
Github : https://github.com/MrLakshay
4+
File : Sudoku Solver
5+
Time Complexity: O(n*n)
6+
Algorithm used: Backtracking
7+
*/
8+
#include <iostream>
9+
#include <math.h>
10+
using namespace std;
11+
bool isSafe(int board[][9], int i, int j, int no, int n)
12+
{
13+
// row and col mai nhi hona chahiye
14+
for (int k = 0; k < n; k++)
15+
{
16+
if (board[i][k] == no || board[k][j] == no)
17+
{
18+
return false;
19+
}
20+
}
21+
22+
// daba checking idhar hogi
23+
n = sqrt(n);
24+
int si = (i / n) * n;
25+
int sj = (j / n) * n;
26+
for (int k = si; k < si + n; k++)
27+
{
28+
for (int l = sj; l < sj + n; l++)
29+
{
30+
if (board[k][l] == no)
31+
{
32+
return false;
33+
}
34+
}
35+
}
36+
return true;
37+
}
38+
bool SudokuSolver(int board[][9], int i, int j, int n)
39+
{
40+
// base case
41+
if (i == n)
42+
{
43+
for (int l = 0; l < 9; l++)
44+
{
45+
for (int m = 0; m < 9; m++)
46+
{
47+
cout << board[l][m] << " ";
48+
}
49+
cout << endl;
50+
}
51+
return true;
52+
}
53+
// recursive case
54+
if (j == n)
55+
{
56+
return SudokuSolver(board, i + 1, 0, n); // agar column n pee pohoch jaye toh niche kaar doo
57+
}
58+
if (board[i][j] != 0)
59+
{
60+
return SudokuSolver(board, i, j + 1, n);
61+
}
62+
for (int no = 1; no < 10; no++)
63+
{
64+
if (isSafe(board, i, j, no, n))
65+
{
66+
board[i][j] = no;
67+
bool baakisolve = SudokuSolver(board, i, j + 1, n);
68+
if (baakisolve)
69+
{
70+
return true;
71+
}
72+
board[i][j] = 0;
73+
}
74+
}
75+
return false;
76+
}
77+
int main()
78+
{
79+
int sudoku[9][9] = {
80+
{3, 0, 6, 5, 0, 8, 4, 0, 0},
81+
{5, 2, 0, 0, 0, 0, 0, 0, 0},
82+
{0, 8, 7, 0, 0, 0, 0, 3, 1},
83+
{0, 0, 3, 0, 1, 0, 0, 8, 0},
84+
{9, 0, 0, 8, 6, 3, 0, 0, 5},
85+
{0, 5, 0, 0, 9, 0, 6, 0, 0},
86+
{1, 3, 0, 0, 0, 0, 2, 5, 0},
87+
{0, 0, 0, 0, 0, 0, 0, 7, 4},
88+
{0, 0, 5, 2, 0, 6, 3, 0, 0}};
89+
SudokuSolver(sudoku, 0, 0, 9);
90+
return 0;
91+
}

0 commit comments

Comments
 (0)