这学期学JAVA,然而之前并没怎么学。
题目
Hyperskill上面的一道题:Check sudoku
输入:
N 为数独小方块的长度(平常做的数独是 N = 3)
数独每个格的数字(N^4 个,N^2 行, N^2 列)
输出:
YES(若所给的数独是正确的)
NO(若所给的数独是错误的)
思路及代码
我的思路很简单,直接检测每行、每列、每个小方块。
是的,并没有用到什么算法和数据结构。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input N and square
int n = scanner.nextInt();
byte[][] table = new byte[n * n][n * n];
for (int i = 0; i < n * n; i++) {
for (int j = 0; j < n * n; j++) {
table[i][j] = scanner.nextByte();
}
}
//System.out.println("Input pass");
// Check all rows, print NO and return if check failed
for (int rowNumber = 0; rowNumber < n * n; rowNumber++) {
byte[] row = getRow(table, rowNumber);
if (!checkItems(row)) {
System.out.println("NO");
return;
}
}
//System.out.println("CheckRow pass");
// Check all cols, print NO and return if check failed
for (int colNumber = 0; colNumber < n * n; colNumber++) {
byte[] col = getCol(table, colNumber);
if (!checkItems(col)) {
System.out.println("NO");
return;
}
}
//System.out.println("CheckCol pass");
// Check all N*N Square, print NO and return if check failed
for (int squareNumber = 0; squareNumber < n * n; squareNumber++) {
byte[] square = getSquare(table, squareNumber, n);
if (!checkItems(square)) {
System.out.println("NO");
return;
}
}
//System.out.println("CheckSquare pass");
// Print yes, cuz it was solved
System.out.println("YES");
}
static byte[] getRow(byte[][] table, int rowNumber) {
byte[] row = new byte[table.length];
for (int i = 0; i < table.length; i++) {
row[i] = table[rowNumber][i];
}
return row;
}
static byte[] getCol(byte[][] table, int colNumber) {
byte[] col = new byte[table.length];
for (int i = 0; i < table.length; i++) {
col[i] = table[i][colNumber];
}
return col;
}
static byte[] getSquare(byte[][] table, int squareNumber, int n) {
byte[] square = new byte[table.length];
int k = 0; // square的下标
int startRow = (squareNumber / n) * n;
int startCol = (squareNumber % n) * n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
square[k] = table[startRow + i][startCol + j];
k++;
}
}
return square;
}
/**
* @param items: 可以为 row col square(小),含有maxNumber个数
* @return: 若items中出现重复数字或错误的数字,返回false。否则返回true。
*/
static boolean checkItems(byte[] items) {
// maxNumber, or say n^2
int maxNumber = items.length;
boolean[] isPresent = new boolean[maxNumber + 1];
for (int i = 1; i <= maxNumber; i++) {
isPresent[i] = false;
}
for (byte number : items) {
// 如果发现数字越界、数字重复,则说明有误
if (number < 1 || number > maxNumber) {
return false;
} else if (isPresent[number]) {
return false;
} else {
isPresent[number] = true;
}
}
return true;
}
}