Problem Description
数独是一种流行的单人游戏。
目标是用数字填充9x9矩阵,使每列,每行和所有9个非重叠的3x3子矩阵包含从1到9的所有数字。
每个9x9矩阵在游戏开始时都会有部分数字已经给出,通常有一个独特的解决方案。
给定完成的N2 ∗ N2数独矩阵,你的任务是确定它是否是有效的解决方案。
有效的解决方案必须满足以下条件:
- 每行包含从1到N2的每个数字,每个数字一次。
- 每列包含从1到N2的每个数字,每个数字一次。
- 将N2∗N2矩阵划分为N2个非重叠N∗N子矩阵。 每个子矩阵包含从1到N2的每个数字,每个数字一次。
你无需担心问题的唯一性,只需检查给定矩阵是否是有效的解决方案即可。
Input Format
第一行包含整数T,表示共有T组测试数据。
每组数据第一行包含整数N。
接下来N2行,每行包含N2个数字(均不超过1000),用来描述完整的数独矩阵。
Output Format
每组数据输出一个结果,每个结果占一行。
结果表示为“Case #x: y”,其中x是组别编号(从1开始),如果给定矩阵是有效方案则y是Yes,否则y是No。
Scope of Data
1 ≤ T ≤ 100,
3 ≤ N ≤ 6
Sample Input
3
3
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
3
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
3
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 999 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
Sample Output
Case #1: Yes
Case #2: No
Case #3: No
Idea
分别枚举数独每行、每列、每个子矩阵,判断是否合规
Program Code
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 40;
int n,T;
int sudoku[N][N];
int t;
bool Judge[N];
bool Judge_Row() //判断每行
{
for(int i = 1; i <= t; ++ i) //表示行
{
memset(Judge, false, N * sizeof(bool)); //每次均初始化为false,避免遗留上次结果
for(int j = 1; j <= t; ++ j) //表示列
{
if(sudoku[i][j] > t || sudoku[i][j] < 1) //if数据异常
return false;
else
Judge[sudoku[i][j]] = true;
}
for(int x = 1; x <= t; ++ x)
{
if(Judge[x])
continue;
else
return false;
}
}
return true;
}
bool Judge_Column() //判断每列
{
for(int i = 1; i <= t; ++ i) //表示列
{
memset(Judge, false, N * sizeof(bool)); //每次均初始化为false,避免遗留上次结果
for(int j = 1; j <= t; ++ j) //表示行
{
if(sudoku[j][i] > t || sudoku[j][i] < 1) //if数据异常
return false;
else
Judge[sudoku[j][i]] = true;
}
for(int x = 1; x <= t; ++ x)
{
if(Judge[x])
continue;
else
return false;
}
}
return true;
}
bool Judge_Submatrix() //判断子矩阵
{
for(int i = 1; i <= n; i ++) //以n为单位表示行
{
for(int j = 1; j <= n; j ++) //以n为单位表示列
{
memset(Judge, false, N * sizeof(bool)); //每次均初始化为false,避免遗留上次结果
for(int x = (i - 1) * n + 1; x <= i * n; ++ x) //表示子矩阵的行
for(int y = (i -1) * n + 1; y <= i * n; ++ y) //表示子矩阵的列
{
if(sudoku[x][y] > t || sudoku[x][y] < 1) //数据异常
return false;
else
Judge[sudoku[x][y]] = true;
}
for(int x = 1; x <= t; ++ x)
{
if(Judge[x])
continue;
else
return false;
}
}
}
return true;
}
int main()
{
int cnt = 0;
cin >> T;
while(T --)
{
cin >> n;
t = n * n;
cnt ++; //计数
for(int i = 1; i <= t; ++ i)
for(int j = 1; j <= t; ++ j)
cin >> sudoku[i][j];
if (Judge_Row() && Judge_Column() && Judge_Submatrix())
printf("Case #%d: Yes\n", cnt);
else
printf("Case #%d: No\n", cnt);
}
return 0;
}
- If you have any questions,please feel free to communicate with me.