-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathValid_Sudoku.java
More file actions
56 lines (50 loc) · 1.19 KB
/
Valid_Sudoku.java
File metadata and controls
56 lines (50 loc) · 1.19 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
package Array;
public class Valid_Sudoku {
public static void main(String[] args) {
}
public boolean isValidSudoku(char[][] board) {
return isValidSudoku(board, 9);
}
public boolean isValidSudoku(char[][] board, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
char val = board[i][j];
if (val != '.') {
if (!safe(board, i, j, val)) {
return false;
}
}
}
}
return true;
}
public boolean safe(char[][] board, int row, int col, char val) {
for (int r = 0; r < 9; r++) {
if (r == row) {
continue;
} else if (board[r][col] == val) {
return false;
}
}
for (int c = 0; c < 9; c++) {
if (c == col) {
continue;
} else if (board[row][c] == val) {
return false;
}
}
int sqrt = (int) Math.sqrt(9);
int rs = row - row % sqrt;
int cs = col - col % sqrt;
for (int i = rs; i < rs + sqrt; i++) {
for (int j = cs; j < cs + sqrt; j++) {
if (i == row && j == col) {
continue;
} else if (board[i][j] == val) {
return false;
}
}
}
return true;
}
}