-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathValidSudoku.java
More file actions
40 lines (39 loc) · 1.44 KB
/
ValidSudoku.java
File metadata and controls
40 lines (39 loc) · 1.44 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
package swe;
import java.util.*;
public class ValidSudoku {
public static boolean isValidSudoku(int[][] board) {
for (int i = 0; i < 9; i++) {
Set<Integer> row = new HashSet<>();
Set<Integer> colum = new HashSet<>();
Set<Integer> box = new HashSet<>();
for (int j = 0; j < 9; j++) {
if (board[i][j] != 0 && !row.add(board[i][j])) {
return false;
}
if (board[j][i] != 0 && !colum.add(board[j][i])) {
return false;
}
int boxRow = 3 * (i / 3) + j / 3;
int boxColum = 3 * (i % 3) + j % 3;
if (board[boxRow][boxColum] != 0 && !box.add(board[boxRow][boxColum])) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
int[][] board = {
{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}
};
System.out.println("Valid Sudoku " + isValidSudoku(board));
}
}