hdu5547 Sudoku (暴力DFS)

题目点我点我点我
CCPC的H题,当时现场赛是连DFS都不会啊,唉o(︶︿︶)o
题目大意:数独
思路:直接暴力DFS,row[i][k]第i行数字为k的,col[i][k]第i列数字为k的。2*2的方块也必须是1234。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define inf 0x3f3f3f3f
pair<int,int>p[18];
int row[5][5],col[5][5],num,flag;  //flag控制输出及递归的结束
char s[5][5];

bool check() //2*2的方块是否都有1234
{
    if(((1<<s[1][1])|(1<<s[1][2])|(1<<s[2][1])|(1<<s[2][2]))!=30)return false;
    if(((1<<s[1][3])|(1<<s[1][4])|(1<<s[2][3])|(1<<s[2][4]))!=30)return false;
    if(((1<<s[3][1])|(1<<s[3][2])|(1<<s[4][1])|(1<<s[4][2]))!=30)return false;
    if(((1<<s[3][3])|(1<<s[3][4])|(1<<s[4][3])|(1<<s[4][4]))!=30)return false;
    return true;
}

void dfs(int cnt)
{
    if(flag)return;
    if(cnt>num)
    {
        if(check())
        {
            flag=1;  
            for(int i=1;i<=4;i++)
            {
                for(int j=1;j<=4;j++)
                {
                    s[i][j]+='0';
                     cout<<(s[i][j]);
                }
                printf("\n");
            }
        }
        return;
    }
    int x=p[cnt].first;
    int y=p[cnt].second;
    for(int i=1;i<=4;i++)
    {
        if(!row[x][i] && !col[y][i])
        {
            row[x][i]=1;
            col[y][i]=1;
            s[x][y]=i;
            dfs(cnt+1);
            row[x][i]=0;
            col[y][i]=0;
        }
    }
    if(flag)return;

}


int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int T,i,j,cas=1;
    scanf("%d",&T);
    while(T--)
    {
        memset(row,0,sizeof(row));
        memset(col,0,sizeof(col));
        num=0;
        flag=0;
        for(i=1;i<=4;i++)
        {
            for(j=1;j<=4;j++)
            {
                cin>>s[i][j];
                if(s[i][j]!='*')
                {
                    s[i][j]-='0';
                    int k=s[i][j];
                    row[i][k]=1;
                    col[j][k]=1;
                }
                else
                {
                    p[++num]=make_pair(i,j); //*的行列记录下来
                    s[i][j]-='0';

                }
            }
        }
        printf("Case #%d:\n",cas++);
        dfs(1);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值