forked from hash-define-organization/Hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSudoku Solver
115 lines (78 loc) · 2.8 KB
/
Sudoku Solver
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
import java.util.*;
public class SudokuSolver {
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[][] board = new int[n][n];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
board[i][j] = scn.nextInt();
}
// System.out.println();
}
Sudoku(board, 0, 0);
display(board);
}
public static boolean Sudoku(int[][] board, int row, int col) {
if (col == board[0].length) {
row = row + 1;
col = 0;
}
if (row == board.length) {
// display(board);
return true;
}
if (board[row][col] != 0) {
return Sudoku(board, row, col + 1);
}
for (int i = 1; i <= 9; i++) {
if (isItSafe(board, row, col, i)) {
board[row][col] = i;
boolean res = Sudoku(board, row, col + 1);
if (res)
return true;
board[row][col] = 0;
}
}
return false;
}
public static boolean isItSafe(int[][] board, int row, int col, int val) {
return isItSafeRow(board, row, val) && isItSafeCol(board, col, val) && isItSafeCell(board, row, col, val);
}
public static boolean isItSafeRow(int[][] board, int row, int val) {
for (int col = 0; col < board[0].length; col++) {
if (board[row][col] == val) {
return false;
}
}
return true;
}
public static boolean isItSafeCol(int[][] board, int col, int val) {
for (int row = 0; row < board.length; row++) {
if (board[row][col] == val) {
return false;
}
}
return true;
}
public static boolean isItSafeCell(int[][] board, int row, int col, int val) {
int rs = row - row % 3;
int cs = col - col % 3;
for (int r = rs; r < rs + 3; r++) {
for (int c = cs; c < cs + 3; c++) {
if (board[r][c] == val) {
return false;
}
}
}
return true;
}
public static void display(int[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}