forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SudokuSolver.c
132 lines (120 loc) · 2.53 KB
/
SudokuSolver.c
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
/*
SudokuSolver
Given a partially filled 9×9 2D array grid[9][9], the goal is to assign digits (from 1 to 9)
to the empty cells so that every row, column, and subgrid of size 3×3 contains exactly one instance
of the digits from 1 to 9.
*/
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
bool isSafeToPut(int mat[][9], int i, int j, int n, int number)
{
// Check the rows and cols
for (int k = 0; k < n; k++)
{
if (mat[k][j] == number)
{
return false;
}
}
for (int k = 0; k < n; k++)
{
if (mat[i][k] == number)
{
return false;
}
}
n = sqrt(n);
int starti = (i / n) * n;
int startj = (j / n) * n;
for (int k = starti; k < starti + n; k++)
{
for (int l = startj; l < startj + n; l++)
{
if (mat[k][l] == number)
{
return false;
}
}
}
return true;
}
bool SudokuSolver(int mat[][9], int i, int j, int n)
{
if (i == n)
{
// Print the sudoku
printf("\nSolved Sudoku:\n");
for (int k = 0; k < n; k++)
{
for (int l = 0; l < n; l++)
{
printf("%d ", mat[k][l]);
}
printf("\n");
}
printf("\n");
return true;
}
if (j == n)
{
return SudokuSolver(mat, i + 1, 0, n);
}
if (mat[i][j] != 0)
{
return SudokuSolver(mat, i, j + 1, n);
}
for (int number = 1; number <= n; number++)
{
if (isSafeToPut(mat, i, j, n, number))
{
mat[i][j] = number;
bool t = SudokuSolver(mat, i, j + 1, n);
if (t)
{
return true;
}
mat[i][j] = 0;
}
}
return false;
}
int main()
{
int mat[9][9];
printf("Enter elements and type 0 for empty cells:\n");
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
scanf("%d", &mat[i][j]);
}
}
SudokuSolver(mat, 0, 0, 9);
return 0;
}
/*
Sample input/output:
Enter elements and type 0 for empty cells:
3 0 6 5 0 8 4 0 0
5 2 0 0 0 0 0 0 0
0 8 7 0 0 0 0 3 1
0 0 3 0 1 0 0 8 0
9 0 0 8 6 3 0 0 5
0 5 0 0 9 0 6 0 0
1 3 0 0 0 0 2 5 0
0 0 0 0 0 0 0 7 4
0 0 5 2 0 6 3 0 0
Solved Sudoku:
3 1 6 5 7 8 4 9 2
5 2 9 1 3 4 7 6 8
4 8 7 6 2 9 5 3 1
2 6 3 4 1 5 9 8 7
9 7 4 8 6 3 1 2 5
8 5 1 7 9 2 6 4 3
1 3 8 9 4 7 2 5 6
6 9 2 3 5 1 8 7 4
7 4 5 2 8 6 3 1 9
Time complexity: O(9^(n*n))
Space Complexity: O(n*n)
*/