Repository navigation
Expand file tree
/
Copy pathSudoku.java
More file actions
71 lines (66 loc) · 2.03 KB
/
Copy pathSudoku.java
File metadata and controls
71 lines (66 loc) · 2.03 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
import java.util.Scanner;
public class Sudoku
{
public static void main (String[] args)
{
int[][] grid = readASolution();
System.out.println(isValid(grid) ? "Valid solution" : "Invalid solution");
}
public static int[][] readASolution() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sudoku puzzle solution");
int[][] grid = new int[9][9];
for(int i=0; i<9; i++) {
for(int j=0; j<9; j++) {
grid[i][j] = input.nextInt();
}
}
return grid;
}
public static boolean isValid(int[][] grid){
//check rows
for(int i = 0; i < 9; i++) {
if (!is1To9(grid[i])){
return false;
}
}
//check columns
for (int j=0; j<9; j++) {
int[] column = new int[9];
for(int i=0; i<9; i++) {
column[i] = grid[i][j];
}
if (!is1To9(column)){
return false;
}
}
//check cells
for (int i=0; i<3; i++){
for (int j=0; j<3; j++) {
//starting element in the 3x3 box
int k = 0;
int[] list = new int[9];
for(int row = i * 3; row < i* 3 + 3; row++) {
for (int column = j * 3; column < j * 3 + 3; column++) {
list[k++] = grid[row][column];
}
}
if (!is1To9(list)) {
return false;
}
}
}
return true;
}
public static boolean is1To9(int[] list) {
int[] temp = new int[list.length];
System.arraycopy(list, 0, temp, 0, list.length);
java.util.arrays.sort(temp);
for(int i = 0; i < 9; i++) {
if (temp[i] != i+1) {
return false;
}
return true;
}
}
}