Ku Nole Ku Nole - 20 days ago 9
Java Question

How to implement check if Sudoku is valid in Java?

I'd would like to implement a check to see if a sudoku is valid in Java, and came across (http://leetcode.tgic.me/valid-sudoku/index.html).

I understand how it is validating rows and columns, but for the 3x3 grids validator:

34 for(x = 0; x < mx; x += 3){
35 for(y = 0; y < my; y += 3){
36
37 HashSet<Character> block = new HashSet<Character>();
38
39 for(int offset = 0; offset < 9; offset++){
40 int ox = offset % 3;
41 int oy = offset / 3;
42
43 char c = board[x + ox][y + oy];
44 if(c != '.'){
45 if(block.contains(c)) return false;
46
47 block.add(c);
48 }
49 }
50 }
51 }


What is
offset
and how does it help to check every cell in the 3x3 grid? I brute forced it and tried
x=0, y=0
,
offset=0
and
offset=1
first, but
offset=1
gives
int ox = 1%3 = 1;
and
int oy = 1/3
, so the
board[0 + 1][0+(1/3)] = board[1][1/3]
, and what does cell
[1/3]
represent and so on?

Answer

when you divide n by m, both are int's (either literals or variables) the result is also an int, so 1/3 -> 0 Hence when offset == 0 => ox=0, oy=0 offset == 1 => ox=1, oy=0 offset == 2 => ox=2, oy=0 offset == 3 -> ox=0, oy=1 ... hence you will loop nicely of the 3 rows and 3 columns

Comments