【HDOJ】(1426)Sudoku Killer (dfs) Sudoku Killer

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 1   Accepted Submission(s) : 1

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

Problem Description



答案:
【HDOJ】(1426)Sudoku Killer (dfs)
Sudoku Killer

Input

本题包含多组测试,每组之间由一个空行隔开。每组测试会给你一个 9*9 的矩阵,同一行相邻的两个元素用一个空格分开。其中1-9代表该位置的已经填好的数,问号(?)表示需要你填的数。

Output

对于每组测试,请输出它的解,同一行相邻的两个数用一个空格分开。两组解之间要一个空行。
对于每组测试数据保证它有且只有一个解。

Sample Input

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

Sample Output

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

Author

linle

Source

ACM暑期集训队练习赛(三)

思路:判断行列和周围九格

#include<bits/stdc++.h>
using namespace std;
int a[10][10];
int num;
struct zz
{
    int x,y;
} b[107];
int check(int k,int t)
{
    for(int i=0; i<9; i++) //行列
    {
        if(a[b[t].x][i]==k||a[i][b[t].y]==k)
            return 0;
    }
    int q,p;
    q=(b[t].x/3)*3;
    p=(b[t].y/3)*3;
    for(int i=q; i<q+3; i++)
    {
        for(int j=p; j<p+3; j++)
        {
            if(a[i][j]==k)
                return 0;
        }
    }
    return 1;
}
void dfs(int t)
{
    if(t==num)
    {
        for(int i=0; i<9; i++)
        {
            for(int j=0; j<8; j++)
                cout<<a[i][j]<<" ";
            cout<<a[i][8]<<endl;
        }
        return;
    }

    for(int i=1; i<=9; i++)
    {
        if(check(i,t))//可以放
        {
            a[b[t].x][b[t].y]=i;
            dfs(t+1);
            a[b[t].x][b[t].y]=0;
        }
    }

    return ;
}
int main()
{
    char s;
    int q=0;
    while(cin>>s)
    {
        num=0;
        if(s=='?')
        {
            b[num].x=0;
            b[num].y=0;
            num++;
            a[0][0]=0;
        }
        else
        {
            a[0][0]=s-'0';
        }
        int i,j;
        for(i=0; i<9; i++)
        {
            for(j=0; j<9; j++)
            {
                if(j==0&&i==0)
                    continue;
                cin>>s;
                if(s=='?')
                {
                    b[num].x=i;
                    b[num].y=j;
                    num++;
                    a[i][j]=0;
                }
                else
                {
                    a[i][j]=s-'0';
                }
            }
        }
        if(q++)//用来换行
            cout<<endl;
        dfs(0);

    }
    return 0;
}