数独

数独

样例输入:

* 2 6 * * * * * *
* * * 5 * 2 * * 4
* * * 1 * * * * 7
* 3 * * 2 * 1 8 *
* * * 3 * 9 * * *
* 5 4 * 1 * * 7 *
5 * * * * 1 * * *
6 * * 9 * 7 * * *
* * * * * * 7 5 *

思路

从第一个点(本题是0,0)开始深搜,先写边界条件。当越界时进行处理;当找到时输出并设置标记退出DFS。

其他情况(可以填数)从1--9开始遍历填数,并检查横、竖、小方格是否有重复的数字。符合条件则填上去然后从下一个点开始继续搜索,搜完后没有结束则取消填数,进行其他填数的尝试

import java.util.*;
import java.math.*;

public class Main {

	static int[][] map = new int[9][9];
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        
        boolean f = false;
        int x = 0;
        int y = 0;
        for(int i=0; i<9; i++) {
        	for(int j=0; j<9; j++) {
        		String c = cin.next();
        		if(c.equals("*")) {
        			if(!f) {
        				f = true;
        				x = i;
        				y = j;
        			}
        			map[i][j] = 0;
        		}
        		else map[i][j] = Integer.valueOf(c);
        	}
        }
        dfs(0, 0);
       
    }
    static boolean flag = false;
    private static void dfs(int x,int y) {
    	if(flag) return ;
    	if(y == 9) {
    		x++; y = 0;
    	}
    	if(x == 9) {
    		flag = true;
			for(int i=0; i<9; i++) {
			    for(int j=0; j<9; j++) {
			    	System.out.print(map[i][j]+" ");
				}
				System.out.println();
			}
    		return ;
    	}
    	
    	if(map[x][y] == 0) {
    		for(int i=1; i<=9; i++) {
        		if(check(x, y, i)) {
        			map[x][y] = i;
        			dfs(x, y + 1);
        			map[x][y] = 0;
        		}
        	}
    	}
    	else {
    		dfs(x, y + 1);
    	}
	}

	static boolean[] vis = new boolean[10];
	private static boolean check(int x, int y, int val) {
		Arrays.fill(vis, false);
		for(int i=0; i<9; i++) {
			int t = map[x][i];
			if(t != 0) vis[t] = true;
			t = map[i][y];
			if(t != 0) vis[t] = true;
		}
		int row = x/3*3;
		int col = y/3*3;
		for(int i=row; i<=row+2; i++) {
			for(int j=col; j<=col+2; j++) {
				int t = map[i][j];
				if(t != 0) vis[t] = true;
			}
		}
		if(vis[val] == true) return false;
		return true;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值