您的位置:首页 > 其它

【蓝桥杯】 数独游戏 (经典深搜题型)

2018-03-23 15:57 309 查看
你一定听说过“数独”游戏。
如【图1.png】,玩家需要根据9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个同色九宫内的数字均含1-9,不重复。
数独的答案都是唯一的,所以,多个解也称为无解。
本图的数字据说是芬兰数学家花了3个月的时间设计出来的较难的题目。但对会使用计算机编程的你来说,恐怕易如反掌了。
本题的要求就是输入数独题目,程序输出数独的唯一解。我们保证所有已知数据的格式都是合法的,并且题目有唯一的解。
格式要求,输入9行,每行9个字符,0代表未知,其它数字为已知。
输出9行,每行9个数字表示数独的解。

例如:
输入(即图中题目):
005300000
800000020
070010500
400005300
010070006
003200080
060500009
004000030
000009700

程序应该输出:
145327698
839654127
672918543
496185372
218473956
753296481
367542819
984761235
521839764

再例如,输入:
800000000
003600000
070090200
050007000
000045700
000100030
001000068
008500010
090000400

程序应该输出:
812753649
943682175
675491283
154237896
369845721
287169534
521974368
438526917
796318452
分析:典型的深度搜索,要注意写判断条件。二维数组从(1,1)开始, 代码中有注释,可以结合注释来阅读。import java.util.Scanner;

public class Main {
public static int[][] map= new int[10][10];
public static boolean isOk(int row,int col ,int num) //判断在第row行,col列,以及九宫格中能不能放num值
{
for(int i=1;i<=9;i++)
{
if(map[row][i] == num) return false; //对行的判断
}
for(int i=1;i<=9;i++)
{
if(map[i][col] == num) return false;
}
int row1,col1;
if(row>=1 && row<=3) //对九宫格的判断
{
row1=1;
}else if( row>=4 && row<=6)
{
row1=4;
}else {
row1=7;
}
if(col>=1&& col<=3)
{
col1=1;
}else if(col>=4 && col<=6)
{
col1=4;
}else {
col1=7;
}
for(int i=row1;i<=row1+2;i++)
for(int j=col1;j<=col1+2;j++)
{
if(map[i][j] ==num ) return false;
}
return true;
}
public static void dfs(int row,int col)
{
if( row == 10)
{
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
{
System.out.print(map[i][j]);
}
System.out.println();
}
return;
}
if(map[row][col] !=0 )
{
dfs(row+(col+1)/10,(col+1)%10);
}else {
for(int num=1;num<=9;num++)
{
if(isOk(row, col, num))
{
map[row][col] = num;
dfs(row+(col+1)/10,(col+1)%10);
map[row][col] = 0; //回溯
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for(int i=0;i<=9;i++) //对地图边界处理
{
map[0][i] = -1;
map[i][0] = -1;
}
for(int row=1; row<=9;row++) //对地图的初始化
{
String s = in.next();
for(int col=1;col<=9;col++)
{
map[row][col] = s.charAt(col-1)-'0';
}
}
dfs(1,1); //进行深搜

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: