数独游戏 dfs

题目描述

你一定听说过“数独”游戏。
如图,玩家需要根据9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个同色九宫内的数字均含1-9,不重复。
在这里插入图片描述
格式要求:
输入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

资源约定:
峰值内存消耗 < 256M
CPU消耗 < 2000ms

题目分析

本题典型用dfs
每个非0位置都可能填1-9;采用深度遍历 找出一条合适的路径

代码

package lanqiao;

import java.util.Scanner;

public class 数独游戏 {
	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		char[][] table = new char[9][9];
		for(int i=0;i<9;i++) 
			table[i] = sc.nextLine().toCharArray();
		dfs(table,0,0);
		
	}
	
	public static void dfs(char[][]table,int x,int y) {
		if(x==9) {
			print(table);
			System.exit(0);
		}
		
		if(table[x][y]!='0')dfs(table,x+(y+1)/9,(y+1)%9);
		else
		{
			for(int i=1;i<=9;i++)
			{
				if(check(table,x,y,i)) {
					table[x][y] =(char)('0'+i);
					dfs(table,x+(y+1)/9,(y+1)%9);
					table[x][y]='0';
				}
			}
		}
	}
	private static void print(char[][] table) {
		for(int i =0;i<table.length;i++) {
			for(int j = 0;j<table[0].length;j++) {
				System.out.print(table[i][j]);
			}
			System.out.println();
		}
		
	}

	public static boolean check(char[][] table,int x,int y,int m)
	{
		for(int i =0 ;i<9;i++) {
			if(table[x][i]=='0'+m)return false;
		}
		for(int i =0 ;i<9;i++) {
			if(table[i][y]=='0'+m)return false;
		}
		return true;
	}

}

注意事项:
1.对每个格子的遍历dfs(table,x+(y+1)/9,(y+1)%9);
2.记得要回溯
3.对这种特殊输入要会处理 具体用到的技巧

char[][] table = new char[9][9];
		for(int i=0;i<9;i++) 
			table[i] = sc.nextLine().toCharArray();
			
table[x][y] =(char)('0'+i);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值