Skip to content

Commit f201c31

Browse files
Update Sudoku.java
1 parent 3aaf7fd commit f201c31

File tree

1 file changed

+144
-59
lines changed
  • src/main/java/com/thealgorithms/puzzlesandgames

1 file changed

+144
-59
lines changed
Lines changed: 144 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,85 +1,170 @@
1-
package sudoku;
21

3-
import java.util.Iterator;
4-
import java.util.NoSuchElementException;
2+
package com.thealgorithms.puzzlesandgames;
53

64
/**
7-
* Represents a Sudoku board with support for iteration using the Iterator pattern.
5+
* A class that provides methods to solve Sudoku puzzles of any n x n size
6+
* using a backtracking approach, where n must be a perfect square.
7+
* The algorithm checks for safe number placements in rows, columns,
8+
* and subgrids (which are sqrt(n) x sqrt(n) in size) and recursively solves the puzzle.
9+
* Though commonly used for 9x9 grids, it is adaptable to other valid Sudoku dimensions.
810
*/
9-
public class SudokuBoard implements Iterable<SudokuBoard.Cell> {
11+
final class Sudoku {
1012

11-
private final int[][] board;
12-
private final int size;
13-
14-
public SudokuBoard(int size) {
15-
this.size = size;
16-
this.board = new int[size][size];
17-
}
18-
19-
public int getSize() {
20-
return size;
13+
private Sudoku() {
2114
}
2215

23-
public int getValue(int row, int col) {
24-
return board[row][col];
25-
}
16+
/**
17+
* Checks if placing a number in a specific position on the Sudoku board is safe.
18+
* The number is considered safe if it does not violate any of the Sudoku rules:
19+
* - It should not be present in the same row.
20+
* - It should not be present in the same column.
21+
* - It should not be present in the corresponding 3x3 subgrid.
22+
* - It should not be present in the corresponding subgrid, which is sqrt(n) x sqrt(n) in size (e.g., for a 9x9 grid, the subgrid will be 3x3).
23+
*
24+
* @param board The current state of the Sudoku board.
25+
* @param row The row index where the number is to be placed.
26+
* @param col The column index where the number is to be placed.
27+
* @param num The number to be placed on the board.
28+
* @return True if the placement is safe, otherwise false.
29+
*/
30+
public static boolean isSafe(int[][] board, int row, int col, int num) {
31+
// Check the row for duplicates
32+
for (int d = 0; d < board.length; d++) {
33+
if (board[row][d] == num) {
34+
return false;
35+
}
36+
}
2637

27-
public void setValue(int row, int col, int value) {
28-
board[row][col] = value;
29-
}
38+
// Check the column for duplicates
39+
for (int r = 0; r < board.length; r++) {
40+
if (board[r][col] == num) {
41+
return false;
42+
}
43+
}
3044

31-
/** Represents a single cell in the Sudoku board */
32-
public static class Cell {
33-
private final int row;
34-
private final int col;
35-
private final int value;
45+
// Check the corresponding 3x3 subgrid for duplicates
46+
int sqrt = (int) Math.sqrt(board.length);
47+
int boxRowStart = row - row % sqrt;
48+
int boxColStart = col - col % sqrt;
3649

37-
public Cell(int row, int col, int value) {
38-
this.row = row;
39-
this.col = col;
40-
this.value = value;
50+
for (int r = boxRowStart; r < boxRowStart + sqrt; r++) {
51+
for (int d = boxColStart; d < boxColStart + sqrt; d++) {
52+
if (board[r][d] == num) {
53+
return false;
54+
}
55+
}
4156
}
4257

43-
public int getRow() {
44-
return row;
45-
}
58+
return true;
59+
}
4660

47-
public int getCol() {
48-
return col;
61+
/**
62+
* Solves the Sudoku puzzle using backtracking.
63+
* The algorithm finds an empty cell and tries placing numbers
64+
* from 1 to n, where n is the size of the board
65+
* (for example, from 1 to 9 in a standard 9x9 Sudoku).
66+
* The algorithm finds an empty cell and tries placing numbers from 1 to 9.
67+
* The standard version of Sudoku uses numbers from 1 to 9, so the algorithm can be
68+
* easily modified for other variations of the game.
69+
* If a number placement is valid (checked via `isSafe`), the number is
70+
* placed and the function recursively attempts to solve the rest of the puzzle.
71+
* If no solution is possible, the number is removed (backtracked),
72+
* and the process is repeated.
73+
*
74+
* @param board The current state of the Sudoku board.
75+
* @param n The size of the Sudoku board (typically 9 for a standard puzzle).
76+
* @return True if the Sudoku puzzle is solvable, false otherwise.
77+
*/
78+
public static boolean solveSudoku(int[][] board, int n) {
79+
int row = -1;
80+
int col = -1;
81+
boolean isEmpty = true;
82+
83+
// Find the next empty cell
84+
for (int i = 0; i < n; i++) {
85+
for (int j = 0; j < n; j++) {
86+
if (board[i][j] == 0) {
87+
row = i;
88+
col = j;
89+
isEmpty = false;
90+
break;
91+
}
92+
}
93+
if (!isEmpty) {
94+
break;
95+
}
4996
}
5097

51-
public int getValue() {
52-
return value;
98+
// No empty space left
99+
if (isEmpty) {
100+
return true;
53101
}
54-
}
55102

56-
/** Iterator implementation for Sudoku board cells */
57-
private class CellIterator implements Iterator<Cell> {
58-
private int row = 0;
59-
private int col = 0;
60-
61-
@Override
62-
public boolean hasNext() {
63-
return row < size && col < size;
103+
// Try placing numbers 1 to n in the empty cell (n should be a perfect square)
104+
// Eg: n=9 for a standard 9x9 Sudoku puzzle, n=16 for a 16x16 puzzle, etc.
105+
for (int num = 1; num <= n; num++) {
106+
if (isSafe(board, row, col, num)) {
107+
board[row][col] = num;
108+
if (solveSudoku(board, n)) {
109+
return true;
110+
} else {
111+
// replace it
112+
board[row][col] = 0;
113+
}
114+
}
64115
}
116+
return false;
117+
}
65118

66-
@Override
67-
public Cell next() {
68-
if (!hasNext()) {
69-
throw new NoSuchElementException();
119+
/**
120+
* Prints the current state of the Sudoku board in a readable format.
121+
* Each row is printed on a new line, with numbers separated by spaces.
122+
*
123+
* @param board The current state of the Sudoku board.
124+
* @param n The size of the Sudoku board (typically 9 for a standard puzzle).
125+
*/
126+
public static void print(int[][] board, int n) {
127+
// Print the board in a nxn grid format
128+
// if n=9, print the board in a 9x9 grid format
129+
// if n=16, print the board in a 16x16 grid format
130+
for (int r = 0; r < n; r++) {
131+
for (int d = 0; d < n; d++) {
132+
System.out.print(board[r][d]);
133+
System.out.print(" ");
70134
}
71-
Cell cell = new Cell(row, col, board[row][col]);
72-
col++;
73-
if (col == size) {
74-
col = 0;
75-
row++;
135+
System.out.print("\n");
136+
137+
if ((r + 1) % (int) Math.sqrt(n) == 0) {
138+
System.out.print("");
76139
}
77-
return cell;
78140
}
79141
}
80142

81-
@Override
82-
public Iterator<Cell> iterator() {
83-
return new CellIterator();
143+
/**
144+
* The driver method to demonstrate solving a Sudoku puzzle.
145+
* A sample 9x9 Sudoku puzzle is provided, and the program attempts to solve it
146+
* using the `solveSudoku` method. If a solution is found, it is printed to the console.
147+
*
148+
* @param args Command-line arguments (not used in this program).
149+
*/
150+
public static void main(String[] args) {
151+
int[][] board = new int[][] {
152+
{3, 0, 6, 5, 0, 8, 4, 0, 0},
153+
{5, 2, 0, 0, 0, 0, 0, 0, 0},
154+
{0, 8, 7, 0, 0, 0, 0, 3, 1},
155+
{0, 0, 3, 0, 1, 0, 0, 8, 0},
156+
{9, 0, 0, 8, 6, 3, 0, 0, 5},
157+
{0, 5, 0, 0, 9, 0, 6, 0, 0},
158+
{1, 3, 0, 0, 0, 0, 2, 5, 0},
159+
{0, 0, 0, 0, 0, 0, 0, 7, 4},
160+
{0, 0, 5, 2, 0, 6, 3, 0, 0},
161+
};
162+
int n = board.length;
163+
164+
if (solveSudoku(board, n)) {
165+
print(board, n);
166+
} else {
167+
System.out.println("No solution");
168+
}
84169
}
85170
}

0 commit comments

Comments
 (0)