-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSoduku.java
91 lines (67 loc) · 1.74 KB
/
Soduku.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.*;
public class Soduku {
public final static int SIZE = 9 ;
public final static int GRID = 3 ;
private static int[][] matrix = new int[SIZE][SIZE] ;
private static int[] numbers = new int[SIZE] ;
public static void main(String[] args) {
int s ;
boolean go_on = true ;
Scanner sc = new Scanner (System.in) ;
for (int i = 0; i < SIZE; i ++) {
for (int j = 0; j < SIZE; j ++) {
s = sc.nextInt() ;
if (s < 1 || s > 9) {
go_on = false ;
break ;
}
matrix[i][j] = s ;
}
}
if (go_on) {
System.out.println(verify());
} else {
System.out.println(go_on);
}
sc.close();
}
public static boolean verify () {
// Verifies the soduku puzzle and returns TRUE if the configuration is valid
// False otherwise.
int counter = 0;
for (int i = 0; i < SIZE; i ++) {
// Check horizontal
for (int j = 0; j < SIZE; j ++) {
numbers[j] = matrix[i][j] ;
}
if (!check_numbers (numbers)) { return false ; }
// Check vertical
for (int j = 0; j < SIZE; j ++) {
numbers[j] = matrix[j][i] ;
}
if (!check_numbers (numbers)) { return false ; }
if (i%3 == 0) { // Check the grid. Only perform this for every first cell in a grid
for (int j = 0; j < SIZE; j += 3) {
counter = 0 ;
for (int x = j; x < j + 3; x ++) {
for (int y = j; y < j + 3; y ++) {
numbers[counter] = matrix[x][y] ;
counter ++ ;
}
}
if (!check_numbers (numbers)) { return false ;}
}
}
}
return true ;
}
private static boolean check_numbers (int[] numbers) {
Arrays.sort (numbers) ;
for (int c = 1; c < SIZE; c ++) {
if (numbers[c-1] == numbers[c]) {
return false;
}
}
return true ;
}
}