【CCPC】hdu 5547 Sudoku【dfs】

题目:hdu 5547 Sudoku

题意:给你一个4*4的数独,让你填其中未知的数
坑点
1:虽然斜线不用满足每个格子唯一,但是4*4的格子分成4个,每个2*2的格子必须满足数独
2:答案不唯一的输出所有的情况,即暴力搜索的时候要回溯。

ac代码:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <cstdio>
#include <cstring>
using namespace std;

const int N = 6;
int mp[N][N];

bool solve(int val ,int pel, int x)
{
    bool flag[5];
    memset(flag,false,sizeof(flag));
    for(int i=0 ;i<4; ++i)
    {
        if(mp[val][i]!=-1)
            flag[ mp[val][i] ] = true;
        if(mp[i][pel]!=-1)
            flag[ mp[i][pel] ] = true;
    }
    int va = val /2,pe = pel / 2;
    for(int i = va*2; i<=va*2+1; ++i)
    {
        for(int j=pe*2; j<=pe*2+1; ++j)
        {
            if(mp[i][j]!=-1)
                flag[ mp[i][j] ] = true;
        }
    }
    if(flag[ x ] == false)
        return true;
    return false;
}
void print()
{
    for(int i=0;i<4;++i)
    {
        for(int j=0;j<4;++j)
            printf("%d",mp[i][j]);
        puts("");
    }
}
void dfs(int cal, int pel)
{
//    printf("you: %d %d %d\n",cal,pel,mp[cal][pel]);
    if(cal==4 && pel == 0)
    {
        print();return ;
    }
    int cal_next = cal,pel_next = pel;
    if(pel==3)
        ++cal_next,pel_next = 0;
    else   //注意些深搜代码不能想当然,逻辑一定要写清楚
        ++pel_next;
    if(mp[cal][pel] == -1)
    {
        for(int i=1;i<=4;++i)
        {
            if(solve(cal,pel,i)){
//                printf("you: %d %d %d\n",cal,pel,i);
                mp[cal][pel] = i;
                dfs(cal_next, pel_next);
            }
        }
        mp[cal][pel] = -1;
    }
    else
        dfs(cal_next,pel_next);
}
int main()
{
    freopen("Input.txt","r",stdin);
//    freopen("OUt.txt","w",stdout);
    int T;
    scanf("%d",&T);
    for(int cas = 1; cas <=T; ++cas)
    {
        string s[5];
        for(int i=0;i<4;++i)
            cin>>s[i];
        for(int i=0; i<4; ++i)
        {
            for(int j=0; j<4; ++j)
            {
                char c = s[i][j];
                if(c!='*')
                    mp[i][j] = (c-'0');
                else
                    mp[i][j] = -1;
            }
        }
        printf("Case #%d:\n",cas);
        dfs(0,0);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值