@@ -54,7 +54,7 @@ public static boolean isValidMove(final int[][] board, final int row, final int
54
54
* @param board The 9x9 Sudoku board
55
55
* @return true if the puzzle is solved, false if no solution exists
56
56
*/
57
- public static boolean solveSudoku (final int [][] board ) {
57
+ public static boolean solveSudokuHelper (final int [][] board ) {
58
58
// Traverse the board
59
59
for (int row = 0 ; row < 9 ; row ++) {
60
60
for (int col = 0 ; col < 9 ; col ++) {
@@ -80,6 +80,69 @@ public static boolean solveSudoku(final int[][] board) {
80
80
return true ; // Sudoku is solved if no empty cells are left
81
81
}
82
82
83
+ /**
84
+ * Check if the given Sudoku board is valid.
85
+ * A valid board has no duplicate numbers in rows, columns, or 3x3 subgrids.
86
+ *
87
+ * @param board The 9x9 Sudoku board
88
+ * @return true if the board is valid, false otherwise
89
+ */
90
+ public static boolean isValidSudoku (final int [][] board ) {
91
+ // Check each row
92
+ for (int i = 0 ; i < 9 ; i ++) {
93
+ boolean [] row = new boolean [10 ];
94
+ for (int j = 0 ; j < 9 ; j ++) {
95
+ if (board [i ][j ] != 0 ) {
96
+ if (row [board [i ][j ]]) {
97
+ return false ;
98
+ }
99
+ row [board [i ][j ]] = true ;
100
+ }
101
+ }
102
+ }
103
+
104
+ // Check each column
105
+ for (int i = 0 ; i < 9 ; i ++) {
106
+ boolean [] col = new boolean [10 ];
107
+ for (int j = 0 ; j < 9 ; j ++) {
108
+ if (board [j ][i ] != 0 ) {
109
+ if (col [board [j ][i ]]) {
110
+ return false ;
111
+ }
112
+ col [board [j ][i ]] = true ;
113
+ }
114
+ }
115
+ }
116
+
117
+ // Check each 3x3 subgrid
118
+ for (int i = 0 ; i < 9 ; i += 3 ) {
119
+ for (int j = 0 ; j < 9 ; j += 3 ) {
120
+ boolean [] grid = new boolean [10 ];
121
+ for (int k = 0 ; k < 3 ; k ++) {
122
+ for (int l = 0 ; l < 3 ; l ++) {
123
+ if (board [i + k ][j + l ] != 0 ) {
124
+ if (grid [board [i + k ][j + l ]]) {
125
+ return false ;
126
+ }
127
+ grid [board [i + k ][j + l ]] = true ;
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ return true ;
135
+ }
136
+
137
+ public static boolean solveSudoku (final int [][] board ) {
138
+ // Check if the board is valid
139
+ if (!isValidSudoku (board )) {
140
+ return false ;
141
+ }
142
+
143
+ return solveSudokuHelper (board );
144
+ }
145
+
83
146
/**
84
147
* Print the current state of the Sudoku board.
85
148
*
0 commit comments