AcWing 703. 数独检查--Java(hashSet去重)
原题链接
简单
作者:
Joma
,
2021-02-02 00:50:25
,
所有人可见
,
阅读 740
使用hashSet存数据,分别检验行,列,小方块范围的数是否满足数据
检查的方式是:每个行,列,小方块内的数字全部存入hashSet,如果hashSet的大小 < n*n 则不满足
注意越界检查
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
public class Main {
static int[][] a = new int[40][40];
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(reader.readLine());
int s = 1;
while (s <= t){
int n = Integer.parseInt(reader.readLine());
int m = n*n;
for (int i = 1; i <= m; i++) {
String[] str = reader.readLine().split(" ");
for (int j = 1; j <= m; j++) {
a[i][j] = Integer.parseInt(str[j - 1]);
}
}
if(check_row(a, n) && check_col(a, n) && check_square(a, n)){
System.out.println("Case #" + s + ": Yes");
}else {System.out.println("Case #" + s + ": No");}
s ++;
}
}
private static boolean check_square(int[][] a, int n) {
int m = n*n;
for (int i = 1; i <= m; i += n) {
for (int j = 1; j <= m; j+= n) {
HashSet<Integer> hashSet = new HashSet<Integer>();
for (int k = i; k <= i + n; k++) {
for (int l = j; l <= j + n; l++) {
hashSet.add(a[k][l]);
}
}
if (hashSet.size() < m) return false;
}
}
return true;
}
private static boolean check_col(int[][] a, int n) {
int m = n*n;
for (int i = 1; i <= m; i++) {
HashSet<Integer> hashSet = new HashSet<Integer>();
for (int j = 1; j <= m; j++) {
if(a[i][j] < 1 || a[i][j] > m) return false;
hashSet.add(a[i][j]);
}
if (hashSet.size() < m) return false;
}
return true;
}
private static boolean check_row(int[][] a, int n) {
int m = n*n;
for (int i = 1; i <= m; i++) {
HashSet<Integer> hashSet = new HashSet<Integer>();
for (int j = 1; j <= m; j++) {
if(a[i][j] < 1 || a[i][j] > m) return false;
hashSet.add(a[j][i]);
}
if (hashSet.size() < m) return false;
}
return true;
}
}
你这个高仿,哈哈哈哈哈
我觉得每个函数都要定义一下m太多余了,可以把m作为参数或者直接定义成static全局变量好一点
您说得对!