3790 - 测试

通过次数

0

提交次数

0

时间限制 : 2 秒 内存限制 : 128 MB

题目输入

题目输出

输入/输出样例

输入格式


                        

输出格式


                        

Java解答

import java.util.Scanner;
public class Main
{
    static int a[][]=new int[9][9];
    static boolean sq[][][]=new boolean[3][3][10],li[][]=new boolean[9][10],ro[][]=new boolean[9][10];
    static int s[]=new int[10],sj,mj=0; 
    //static long start;
    static void stamp(int x,int y,int num){
	    sq[x/3][y/3][num]=li[x][num]=ro[y][num]=true;
    }
    static boolean check(int x,int y,int num){
	    return sq[x/3][y/3][num]||li[x][num]||ro[y][num];
    }
    static void remove(int x,int y,int num){
	    sq[x/3][y/3][num]=li[x][num]=ro[y][num]=false;
    }
    static void init(){
        Scanner scanner = new Scanner(System.in);
        for(int i=0;i<9;i++)
            for(int j=0;j<=9;j++){
                s[j]=0;sq[i/3][i%3][j]=li[i][j]=ro[i][j]=false;
            }
	    for(int i=0;i<9;i++)
		    for(int j=0;j<9;j++){
			    a[i][j]=Integer.parseInt(scanner.next());stamp(i,j,a[i][j]);
			    if(a[i][j]!=0)s[j]++;
		    }
		//start=System.currentTimeMillis();  
	    for(int j=0;j<9;j++)
		    if(s[j]>mj){
			    mj=s[j];sj=j;
			 }
    }
    
    static void ans(){
        //System.out.printf("------------------------------\n");//<<endl;
        for(int i=0;i<9;i++){
            for(int j=0;j<9;j++)
                System.out.printf("%d ",a[i][j]);
            System.out.printf("\n");
        }
        //System.out.printf("------------------------------\n");//<<endl;
    }
    static boolean find=(false);
    static void search(int i,int j,boolean deep){
        if(find)return ;
        if(j==sj&&deep){
            ans();
            //System.out.printf("Time used: %.3f s\n",(System.currentTimeMillis()-start)/1000.0);
            find=true;return ;
        }
        if(j>=9){search(0,0,true);return ;}
        if(i>=9){search(0,j+1,deep);return ;}
        if(a[i][j]!=0){search(i+1,j,deep);return ;}
        for(int k=1;k<=9;k++){
            if(!check(i,j,k)){
                stamp(i,j,k);a[i][j]=k;
                search(i+1,j,deep);
                remove(i,j,k);
            }
        }
        a[i][j]=0;
    }
    public static void main(String[] args){
        //System.out.printf("------------------------------\n");
        init();
        search(0,sj,false);
    }
}