-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSudokuSolver.java
82 lines (78 loc) · 1.91 KB
/
SudokuSolver.java
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
public class SudokuSolver {
public static void main(String[] args) {
}
static boolean sudoku(int[][] board)
{
//first find the empty elements
int n = board.length;
int row = -1;
int col = -1;
boolean empty = false;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(board[i][j]==0)
{
row=i;
col=j;
empty = true;
break;
}
}
if(empty == true)
break;
}
if(empty == false)
{
return true; //sudolu is solved as there is no more empty space
}
for(int number = 1; number < n; number++)
{
if(isSafe(board, row, col, number))
{
board[row][col] = number;
if(sudoku(board))
{
return true;
}
else
{
board[row][col] = 0;
}
}
}
return false;
}
static boolean isSafe(int[][] board, int row, int col, int num)
{
for(int i=0;i<board.length;i++)
{
if(board[row][i]==num)
{
return false;
}
}
for(int i=0;i<board.length;i++)
{
if(board[i][col] == num)
{
return false;
}
}
int sqrt = (int)Math.sqrt(board.length);
int rowStart = row - row%sqrt;
int colStart = col - col%sqrt;
for(int i=rowStart;i<rowStart+sqrt;i++)
{
for(int j=colStart;j<colStart+sqrt;j++)
{
if(board[i][j]==num)
{
return false;
}
}
}
return true;
}
}