Repository navigation
Expand file tree
/
Copy pathSudokuSolver.java
More file actions
82 lines (77 loc) · 2.48 KB
/
Copy pathSudokuSolver.java
File metadata and controls
82 lines (77 loc) · 2.48 KB
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
package Recursion;
public class SudokuSolver {
static boolean isSafe(int[][] board, int row, int col, int num){
for (int i = 0; i < board.length; i++) {
if (board[i][col] == num) {
return false;
}
}
for (int i = 0; i < board[0].length; i++) {
if (board[row][i] == num) {
return false;
}
}
int startRow = row - row % 3;
int startCol = col - col % 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[startRow + i][startCol + j] == num) {
return false;
}
}
}
return true;
}
static void display(int[][] board){
System.out.println("-------------------------");
for (int i = 0; i < board.length; i++) {
System.out.print("| ");
for (int j = 0; j < board[0].length; j++) {
System.out.print(board[i][j]+" ");
if (j % 3 == 2) {
System.out.print("| ");
}
}
System.out.println();
if (i % 3 == 2) {
System.out.println("-------------------------");
}
}
System.out.println();
}
static void sudoku(int[][] board, int row, int col){
if (row >= board.length){
display(board);
return;
}
if (col >= board[0].length) {
sudoku(board, row + 1, 0);
return;
}
if (board[row][col] != 0) {
sudoku(board, row, col + 1);
return;
}
for (int i = 1; i < 10; i++) {
if (isSafe(board, row, col, i)) {
board[row][col] = i;
sudoku(board, row, col + 1);
board[row][col] = 0;
}
}
}
public static void main(String[] args) {
int[][] sudokuBoard = {
{7, 0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 5, 9, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 8, 3, 0, 0, 0},
{0, 0, 0, 6, 0, 0, 9, 7, 0},
{0, 2, 0, 0, 0, 0, 6, 0, 0},
{3, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 4, 0, 0, 0, 9, 0},
{0, 0, 0, 0, 0, 0, 5, 0, 0}
};
sudoku(sudokuBoard, 0, 0);
}
}