-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValid Sudoku
82 lines (73 loc) · 2.24 KB
/
Valid Sudoku
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#
class Solution {
public boolean isValidSudoku(char[][] board) {
Set<Character> row=null;
Set<Character> col=null;
for(int i=0;i<9;i++)
{
//reinitialize the sets so we don't carry over found characters from the previous run
row=new HashSet<>();
col=new HashSet<>();
for(int j=0;j<9;j++)
{
char r=board[i][j];
char c=board[j][i];
if(r!='.')
{
if(row.contains(r))
{
return false;
}
else
row.add(r);
}
if(c!='.')
{
if(col.contains(c))
{
return false;
}
else
col.add(c);
}
}
}
//block
//loop controls advance by 3 each time to jump through the boxes
for(int i=0;i<9;i+=3)
{
for(int j=0;j<9;j+=3)
{
if(!blockCheck(i,j,board))
return false;
}
}
return true;
}
public boolean blockCheck(int idX,int idY,char [][] board)
{
Set<Character> blockSet = new HashSet<>();
int row=idX+3;
int col=idY+3;
//and because i initializes to idX but only goes to rows, we loop 3 times (once for each row)
for(int i=idX;i<row;i++)
{
//and because j initializes to idY but only goes to col, we loop 3 times (once for each row)
for(int j=idY;j<col;j++)
{
if(board[i][j]!='.')
{
if(blockSet.contains(board[i][j]))
{
return false;
}
else
{
blockSet.add(board[i][j]);
}
}
}
}
return true;
}
}