forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidSudoku.java
More file actions
65 lines (60 loc) · 1.57 KB
/
ValidSudoku.java
File metadata and controls
65 lines (60 loc) · 1.57 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
package com.examplehub.leetcode.middle;
/** https://leetcode.com/problems/valid-sudoku/ */
public class ValidSudoku {
public static boolean solution1(char[][] board) {
// travel all rows to check
for (int i = 0; i < 9; i++) {
int[] digitTable = new int[10];
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
digitTable[board[i][j] - '0']++;
}
}
if (containsRepeat(digitTable)) {
return false;
}
}
// travel all columns to check
for (int i = 0; i < 9; i++) {
int[] digitTable = new int[10];
for (int j = 0; j < 9; j++) {
if (board[j][i] != '.') {
digitTable[board[j][i] - '0']++;
}
}
if (containsRepeat(digitTable)) {
return false;
}
}
// travel all sub-box
// TODO
return true;
}
public static boolean containsRepeat(int[] table) {
for (int num : table) {
if (num > 1) {
return true;
}
}
return false;
}
public static boolean solution2(char[][] board) {
int[][] rows = new int[9][9];
int[][] cols = new int[9][9];
int[][][] subBoxes = new int[3][3][9];
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] != '.') {
int index = board[i][j] - '1';
rows[i][index]++;
cols[j][index]++;
subBoxes[i / 3][j / 3][index]++;
if (rows[i][index] > 1 || cols[j][index] > 1 || subBoxes[i / 3][j / 3][index] > 1) {
return false;
}
}
}
}
return true;
}
}