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

50 篇文章 1 订阅
49 篇文章 0 订阅
你一定听说过“数独”游戏。
如【图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);  //进行深搜
	
}
}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值