Sudoku HDU 5547(DFS)

http://acm.hdu.edu.cn/showproblem.php?pid=5547

分析:4*4的数独,除了判断行和列是否有相同的,还应该判断2*2的四个小方框是否有相同的。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <stack>
#include <math.h>

using namespace std;

#define INF 0x3f3f3f3f
const int maxn = 10;

typedef long long LL;
char maps[maxn][maxn];

int Judge(int row, int col)
{
    ///判断列
    for(int i=0; i<4; i++)
    {
        if(maps[row][i]==maps[row][col] && i!=col)
            return 0;
    }

    ///判断行
    for(int i=0; i<4; i++)
    {
        if(maps[i][col]==maps[row][col] && i!=row)
            return 0;
    }

    ///判断2*2的四个小方框是否有相同的
    int Row, Col;

    if(row%2==1) Row=row-1;
    else Row=row;

    if(col%2==1) Col=col-1;
    else Col=col;

    for(int i=Row; i<=Row+1; i++)
    {
        for(int j=Col; j<=Col+1; j++)
        {
            if(maps[i][j]==maps[row][col] && i!=row && j!=col)
                return 0;
        }
    }

    return 1;
}

void DFS(int x)
{
    if(x == 16)
    {
        for(int i=0; i<4; i++)
            printf("%s
", maps[i]);
        return ;
    }

    int row = x / 4;///计算当前行
    int col = x % 4;///计算当前列

    if(maps[row][col]=='*')
    {
        for(int i=1; i<=4; i++)
        {
            maps[row][col] = i + '0';

            if(Judge(row, col))
                DFS(x+1);

            maps[row][col]='*';
        }
    }

    else
        DFS(x+1);
}

int main()
{
    int T, cnt=1;

    scanf("%d", &T);

    while(T --)
    {
        for(int i=0; i<4; i++)
            scanf("%s", maps[i]);

        printf("Case #%d:
", cnt++);
        
        DFS(0);

    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/daydayupacm/p/5772116.html