Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions JavaProjects/SudokuGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
public class SudokuSolver {
private static final int GRID_SIZE = 9;

public static void main(String[] args) {
int[][] board = {
{7, 0, 2, 0, 5, 0, 6, 0, 0},
{0, 0, 0, 0, 0, 3, 0, 0, 0},
{1, 0, 0, 0, 0, 9, 5, 0, 0},
{8, 0, 0, 0, 0, 0, 0, 9, 0},
{0, 4, 3, 0, 0, 0, 7, 5, 0},
{0, 9, 0, 0, 0, 0, 0, 0, 8},
{0, 0, 9, 7, 0, 0, 0, 0, 5},
{0, 0, 0, 2, 0, 0, 0, 0, 0},
{0, 0, 7, 0, 4, 0, 2, 0, 3}
};

if (solveBoard(board)) {
System.out.println("Sudoku solved successfully:");
printBoard(board);
} else {
System.out.println("Unable to solve Sudoku.");
}
}

private static boolean solveBoard(int[][] board) {
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
if (board[row][col] == 0) {
for (int num = 1; num <= GRID_SIZE; num++) {
if (isValidPlacement(board, num, row, col)) {
board[row][col] = num;

if (solveBoard(board)) {
return true;
} else {
board[row][col] = 0;
}
}
}
return false;
}
}
}
return true;
}

private static boolean isValidPlacement(int[][] board, int number, int row, int col) {
for (int i = 0; i < GRID_SIZE; i++) {
if (board[row][i] == number || board[i][col] == number) {
return false;
}
}

int subgridRowStart = (row / 3) * 3;
int subgridColStart = (col / 3) * 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[subgridRowStart + i][subgridColStart + j] == number) {
return false;
}
}
}
return true;
}

private static void printBoard(int[][] board) {
for (int row = 0; row < GRID_SIZE; row++) {
if (row % 3 == 0 && row != 0) {
System.out.println("-----------");
}
for (int col = 0; col < GRID_SIZE; col++) {
if (col % 3 == 0 && col != 0) System.out.print("|");
System.out.print(board[row][col] == 0 ? "." : board[row][col]);
}
System.out.println();
}
}
}