寒假打卡——AcWing703. 数独检查
2021-02-02
703. 数独检查
数独是一种流行的单人游戏。
目标是用数字填充9x9矩阵,使每列,每行和所有9个非重叠的3x3子矩阵包含从1到9的所有数字。
每个9x9矩阵在游戏开始时都会有部分数字已经给出,通常有一个独特的解决方案。
给定完成的N2∗N2数独矩阵,你的任务是确定它是否是有效的解决方案。
有效的解决方案必须满足以下条件:
- 每行包含从1到N^2的每个数字,每个数字一次。
- 每列包含从1到N^2的每个数字,每个数字一次。
- 将N^2∗N^2矩阵划分为N^2个非重叠N∗N子矩阵。 每个子矩阵包含从1到N^2的每个数字,每个数字一次。
你无需担心问题的唯一性,只需检查给定矩阵是否是有效的解决方案即可。
思路
模拟即可
代码:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static Boolean ok(int[][] a, int n){
int m=n*n;
Map<Integer, Integer> mp=new HashMap<Integer,Integer>();
Map<Integer, Integer> mp2=new HashMap<Integer,Integer>();
Integer value;
for(int i=1;i<=m;i++) {
mp.clear();
mp2.clear();
for(int j=1;j<=m;j++) {
//检查每行
int x=a[i][j];
//检查每列
int y=a[j][i];
if(x>m||y>m)return false;
value=mp.get(x);
if(value != null) return false;
mp.put(x,1);
value=mp2.get(y);
if(value != null) return false;
mp2.put(y,1);
}
}
System.out.println("yes");
for(int i=1;i<=m;i++) {
int h=(i+n-1)/n;
int l=i%n;
if(l==0) l=n;
mp.clear();
for(int j=h*n;j>h*n-n;j--){
for(int k=l*n;k>l*n-n;k--) {
int x=a[j][k];
if(x>m) return false;
value= mp.get(x);
if(value != null) return false;
mp.put(x,1);
}
}
}
return true;
}
public static void main(String[] args) {
int T;
Scanner sc=new Scanner(System.in);
T=sc.nextInt();
for(int k=1;k<=T;k++){
int n;
n= sc.nextInt();
int [][]a=new int[100][100];
for(int i=1;i<=n*n;i++) {
for(int j=1;j<=n*n;j++) {
a[i][j]=sc.nextInt();
}
}
if(ok(a,n)==true) {
System.out.println("Case #"+k+": Yes");
}
else {
System.out.println("Case #"+k+": No");
}
}
}
}