搜索专题 S

1   简单描述

数独,在一个9x9的方格中,需要把数字1-9填写到空格当中,并且使方格的每一行和每一列中都包含1-9这九个数字。同时还要保证,空格中用粗线划分成9个3x3的方格也同时包含1-9这九个数字。

2   思路

# include 
using namespace std;
struct Node
{
    int x,y;
}node[100];
int mp[10][10];
bool flag;
int num;
bool check(int k,int t)
{
    for(int i = 0; i < 9; i++)
        if(mp[node[t].x][i] == k || mp[i][node[t].y]==k)
            return false;
    int x = (node[t].x/3)*3;
    int y = (node[t].y/3)*3;
    for(int i = x; i < x + 3; i++)
        for(int j = y; j < y + 3; j++)
            if(mp[i][j] == k)
                return false;
    return true;
}
void DFS(int t)
{
    if(t == num)
    {
        for(int i = 0; i < 9; i++)
        {
            for(int j = 0; j < 8; j++)
                printf("%d ", mp[i][j]);
                printf("%d\n", mp[i][8]);
        }
        flag = 1;
        return;
    }
    else
    {
        for(int i = 1; i <= 9; i++)
        {
            if(check(i,t) && !flag)
            {
                mp[node[t].x][node[t].y] = i;
                DFS(t+1);
                mp[node[t].x][node[t].y] = 0;
            }
        }
    }
}

int main()
{
    bool first = true;
    char str[10];
    while(scanf("%s", &str) != EOF)
    {
        num = 0;
        if(str[0] == '?')
        {
            node[num].x = 0;
            node[num++].y = 0;
            mp[0][0]=0;
        }
        else
            mp[0][0] = str[0]-'0';
        for(int i = 0; i < 9; i++)
            for(int j = 0; j < 9; j++)
            {
                if(i == 0 && j == 0)
                    continue;
                scanf("%s", &str);
                if(str[0] == '?')
                {
                  node[num].x = i;
                  node[num++].y = j;
                  mp[i][j] = 0;

              }
              else
                mp[i][j] = str[0]-'0';
          }
        flag = false;
        if(first)
            first = false;
        else
            printf("\n");
        DFS(0);
    }
    return 0;
}


      

你可能感兴趣的:(搜索)