-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay30s1.java
More file actions
119 lines (102 loc) · 3.56 KB
/
Day30s1.java
File metadata and controls
119 lines (102 loc) · 3.56 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import java.util.Scanner;
import SudokuSolver;
public class Day30s1 {
public static void main(String[] args) {
SudokuSolver solver = new SudokuSolver();
solver.solve();
}
}
class SudokuSolver {
private static final int SIZE = 9;
private static final int EMPTY = 0;
private int[][] board;
private Scanner scanner;
public SudokuSolver() {
this.board = new int[SIZE][SIZE];
this.scanner = new Scanner(System.in);
}
public void solve() {
System.out.println("Sudoku Çözücüye Hoş Geldiniz!");
System.out.println("Lütfen Sudoku bulmacasını girin (0 boş hücreleri temsil eder):");
// Sudoku bulmacasını kullanıcıdan al
for (int i = 0; i < SIZE; i++) {
System.out.println("Satır " + (i + 1) + " için 9 sayı girin (0-9, boşlukla ayrılmış):");
String[] input = scanner.nextLine().split(" ");
for (int j = 0; j < SIZE; j++) {
board[i][j] = Integer.parseInt(input[j]);
}
}
System.out.println("\nGirilen Sudoku Bulmacası:");
printBoard();
if (solveSudoku()) {
System.out.println("\nSudoku Çözüldü!");
printBoard();
} else {
System.out.println("\nBu Sudoku bulmacası çözülemez!");
}
}
private boolean solveSudoku() {
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
if (board[row][col] == EMPTY) {
for (int num = 1; num <= SIZE; num++) {
if (isValid(row, col, num)) {
board[row][col] = num;
// Adım adım çözümü göster
System.out.println("\nAdım:");
printBoard();
if (solveSudoku()) {
return true;
} else {
board[row][col] = EMPTY;
}
}
}
return false;
}
}
}
return true;
}
private boolean isValid(int row, int col, int num) {
// Satır kontrolü
for (int i = 0; i < SIZE; i++) {
if (board[row][i] == num) {
return false;
}
}
// Sütun kontrolü
for (int i = 0; i < SIZE; i++) {
if (board[i][col] == num) {
return false;
}
}
// 3x3 kutu kontrolü
int boxRow = row - row % 3;
int boxCol = col - col % 3;
for (int i = boxRow; i < boxRow + 3; i++) {
for (int j = boxCol; j < boxCol + 3; j++) {
if (board[i][j] == num) {
return false;
}
}
}
return true;
}
private void printBoard() {
System.out.println("+-------+-------+-------+");
for (int i = 0; i < SIZE; i++) {
if (i % 3 == 0 && i != 0) {
System.out.println("+-------+-------+-------+");
}
for (int j = 0; j < SIZE; j++) {
if (j % 3 == 0) {
System.out.print("| ");
}
System.out.print(board[i][j] == EMPTY ? ". " : board[i][j] + " ");
}
System.out.println("|");
}
System.out.println("+-------+-------+-------+");
}
}