1
+ /**
2
+ * Problem Name : Valid Sudoku
3
+ * Concept Involved : 2D Array, Frequency Count
4
+ *
5
+ * Execution Time : 2 ms
6
+ * Memory Consumed : 38.8 mb
7
+ *
8
+ * Solution : We have been given with a Sudoku
9
+ * Puzzle, we have to determine whether the puzzle
10
+ * is valid or not.
11
+ * In order to check the validity every row and column
12
+ * of sudoku must have numbers from 0 to 9 and in a non
13
+ * repeating fashion and same for in every 3x3 block.
14
+ * I have used array based indexing to compute the
15
+ * frequency of elements in every rows, columns and blocks
16
+ * and checking its validity afterwards.
17
+ * If every check is passed then we return True at the end.
18
+ */
19
+ class Solution {
20
+ public boolean isValid (ArrayList <Integer > arr ){
21
+ int [] fre = new int [10 ];
22
+ for (int ele : arr ){
23
+ fre [ele ]++;
24
+ if (fre [ele ] > 1 ){
25
+ return false ;
26
+ }
27
+ }
28
+ return true ;
29
+ }
30
+ public boolean isValidSudoku (char [][] board ) {
31
+ for (int i =0 ; i <9 ; i ++){
32
+ ArrayList <Integer > row = new ArrayList <>();
33
+ for (int j =0 ; j <9 ; j ++){
34
+ if (board [i ][j ] != '.' ){
35
+ int num = board [i ][j ] - '0' ;
36
+ row .add (num );
37
+ }
38
+ }
39
+ if (!isValid (row )){
40
+ return false ;
41
+ }
42
+ }
43
+
44
+ for (int i =0 ; i <9 ; i ++){
45
+ ArrayList <Integer > col = new ArrayList <>();
46
+ for (int j =0 ; j <9 ; j ++){
47
+ if (board [j ][i ] != '.' ){
48
+ int num = board [j ][i ] - '0' ;
49
+ col .add (num );
50
+ }
51
+ }
52
+ if (!isValid (col )){
53
+ return false ;
54
+ }
55
+ }
56
+
57
+ for (int i =0 ; i <9 ; i +=3 ){
58
+ for (int j =0 ; j <9 ; j +=3 ){
59
+ ArrayList <Integer > block = new ArrayList <>();
60
+ for (int k =i ;k <i +3 ;k ++){
61
+ for (int l =j ;l <j +3 ;l ++){
62
+ if (board [k ][l ] != '.' ){
63
+ int num = board [k ][l ] - '0' ;
64
+ block .add (num );
65
+ }
66
+ }
67
+ }
68
+ if (!isValid (block )){
69
+ return false ;
70
+ }
71
+ }
72
+ }
73
+
74
+ return true ;
75
+ }
76
+ }
0 commit comments