-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sudoku.java
67 lines (53 loc) · 1.44 KB
/
Sudoku.java
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
class Sudoku {
int[][] sudo = new int[9][9];
Sudoku(String s) {
char[] c = s.toCharArray();
for (int r = 0; r < 9; ++r)
for (int k = 0; k < 9; ++k)
sudo[r][k] = Character.getNumericValue(c[10*r+k]);
}
void lös() {
if (lösRekursiv(0, 0)) {
for (int r = 0; r < 9; ++r) {
for (int k = 0; k < 9; ++k)
System.out.print(sudo[r][k]+" ");
System.out.println();
}
} else System.out.println("Går ej att lösa");
}
boolean lösRekursiv(int rad, int kol) {
if (kol == 9) { kol = 0; ++rad; }
if (rad == 9) return true;
if (sudo[rad][kol] != 0) return lösRekursiv(rad, kol+1);
int ogiltiga = 0;
for (int i = 0; i < 9; ++i) {
int br = rad/3*3 + i/3, bk = kol/3*3 + i%3;
ogiltiga |= 1<<sudo[br][bk];
ogiltiga |= 1<<sudo[rad][i];
ogiltiga |= 1<<sudo[i][kol];
}
for (int s = 1; s <= 9; ++s) {
if ((ogiltiga & 1<<s) == 0) {
sudo[rad][kol] = s;
boolean res = lösRekursiv(rad, kol+1);
if (res) return true;
}
}
sudo[rad][kol] = 0;
return false;
}
public static void main(String[] args) {
String s = """
000000000
010000020
000000000
000000000
000050000
000000000
000000000
040000030
000000000
""";
new Sudoku(s).lös();
}
}