Skip to content

Commit 819c638

Browse files
authored
Added task 36.
1 parent 1c07022 commit 819c638

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package s0036_valid_sudoku;
2+
3+
public class Solution {
4+
int j1;
5+
int[] i1 = new int[9];
6+
int[] b1 = new int[9];
7+
8+
public boolean isValidSudoku(char[][] board) {
9+
for (int i = 0; i < 9; i++) {
10+
for (int j = 0; j < 9; j++) {
11+
boolean res = checkValid(board, i, j);
12+
if (!res) {
13+
return false;
14+
}
15+
}
16+
}
17+
return true;
18+
}
19+
20+
boolean checkValid(char[][] board, int i, int j) {
21+
if (j == 0) {
22+
j1 = 0;
23+
}
24+
if (board[i][j] == '.') {
25+
return true;
26+
}
27+
int val = board[i][j] - '0';
28+
if (j1 == (j1 | (1 << (val - 1)))) {
29+
return false;
30+
}
31+
j1 |= 1 << (val - 1);
32+
if (i1[j] == (i1[j] | (1 << (val - 1)))) {
33+
return false;
34+
}
35+
i1[j] |= 1 << (val - 1);
36+
int b = (i / 3) * 3 + j / 3;
37+
if (b1[b] == (b1[b] | (1 << (val - 1)))) {
38+
return false;
39+
}
40+
b1[b] |= 1 << (val - 1);
41+
return true;
42+
}
43+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package s0036_valid_sudoku;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.Test;
7+
8+
public class SolutionTest {
9+
@Test
10+
public void isValidSudoku() {
11+
boolean result =
12+
new Solution()
13+
.isValidSudoku(
14+
new char[][] {
15+
{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
16+
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
17+
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
18+
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
19+
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
20+
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
21+
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
22+
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
23+
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}
24+
});
25+
assertThat(result, equalTo(true));
26+
}
27+
}

0 commit comments

Comments
 (0)