|
1 | 1 | classSolution {
|
2 | 2 |
|
3 | 3 | publicbooleanisValidSudoku(char[][]board) {
|
4 |
| -introws =board.length; |
5 |
| -intcols =board[0].length; |
| 4 | +//neetcode solution, slightly modified |
6 | 5 |
|
| 6 | +//a set of the characters that we have already come across (excluding '.' which denotes an empty space) |
7 | 7 | Set<Character>rowSet =null;
|
8 | 8 | Set<Character>colSet =null;
|
9 | 9 |
|
10 |
| -//check for rows |
11 |
| -for (inti =0;i <rows;i++) { |
12 |
| -rowSet =newHashSet<>(); |
13 |
| -for (intj =0;j <cols;j++) { |
14 |
| -if (board[i][j] =='.') { |
15 |
| -continue; |
16 |
| - } |
17 |
| -if (rowSet.contains(board[i][j])) { |
18 |
| -returnfalse; |
19 |
| - } |
20 |
| -rowSet.add(board[i][j]); |
21 |
| - } |
22 |
| - } |
23 | 10 |
|
24 |
| -//check for cols |
25 |
| -for (inti =0;i <cols;i++) { |
| 11 | +for (inti =0;i <9;i++) { |
| 12 | +//reinitialize the sets so we don't carry over found characters from the previous run |
| 13 | +rowSet =newHashSet<>(); |
26 | 14 | colSet =newHashSet<>();
|
27 |
| -for (intj =0;j <rows;j++) { |
28 |
| -if (board[j][i] =='.') { |
29 |
| -continue; |
| 15 | +for (intj =0;j <9;j++) { |
| 16 | +charr =board[i][j]; |
| 17 | +charc =board[j][i]; |
| 18 | +if (r !='.'){ |
| 19 | +if (rowSet.contains(r)){ |
| 20 | +returnfalse; |
| 21 | + }else { |
| 22 | +rowSet.add(r); |
| 23 | + } |
30 | 24 | }
|
31 |
| -if (colSet.contains(board[j][i])) { |
32 |
| -returnfalse; |
| 25 | +if (c !='.'){ |
| 26 | +if (colSet.contains(c)){ |
| 27 | +returnfalse; |
| 28 | + }else { |
| 29 | +colSet.add(c); |
| 30 | + } |
33 | 31 | }
|
34 |
| - |
35 |
| -colSet.add(board[j][i]); |
36 | 32 | }
|
37 | 33 | }
|
38 | 34 |
|
39 | 35 | //block
|
40 |
| -for (inti =0;i <rows;i =i +3) { |
41 |
| -for (intj =0;j <cols;j =j +3) { |
| 36 | +//loop controls advance by 3 each time to jump through the boxes |
| 37 | +for (inti =0;i <9;i =i +3) { |
| 38 | +for (intj =0;j <9;j =j +3) { |
| 39 | +//checkBlock will return true if valid |
42 | 40 | if (!checkBlock(i,j,board)) {
|
43 | 41 | returnfalse;
|
44 | 42 | }
|
45 | 43 | }
|
46 | 44 | }
|
47 |
| - |
| 45 | +//passed all tests, therefore valid board |
48 | 46 | returntrue;
|
49 | 47 | }
|
50 | 48 |
|
51 | 49 | publicbooleancheckBlock(intidxI,intidxJ,char[][]board) {
|
52 | 50 | Set<Character>blockSet =newHashSet<>();
|
| 51 | +//if idxI = 3 and indJ = 0 |
| 52 | +//rows = 6 and cols = 3 |
53 | 53 | introws =idxI +3;
|
54 | 54 | intcols =idxJ +3;
|
| 55 | +//and because i initializes to idxI but only goes to rows, we loop 3 times (once for each row) |
55 | 56 | for (inti =idxI;i <rows;i++) {
|
| 57 | +//same for columns |
56 | 58 | for (intj =idxJ;j <cols;j++) {
|
57 | 59 | if (board[i][j] =='.') {
|
58 | 60 | continue;
|
59 | 61 | }
|
60 |
| - |
| 62 | +
|
61 | 63 | if (blockSet.contains(board[i][j])) {
|
62 | 64 | returnfalse;
|
63 | 65 | }
|
|