hdu 1426 果枫

题意:中文题,此处省。

ac代码:

View Code
#include<iostream>
using namespace std;

int map[12][12];
int k; 
int foat;

struct tree
{
    int i;
    int j;
}node[90];


int check(struct tree n,int p)
{
    int i,j;
    int x,y;

    for(i=1;i<=9;i++)//判断行与列是否已经存在p
    {
        if(map[n.i][i]==p||map[i][n.j]==p)
            return 0;
    }


    if(n.i<4)//以下的一系列if() else语句都是用来找9个小格的小方块中坐上角的坐标
    {
        if(n.j<4)
        {
            x=1;y=1;
        }
        else
            if(n.j<7)
            {
                x=1;y=4;
            }
            else
            {
                x=1;y=7;
            }
    }
    else
        if(n.i<7)
        {
            if(n.j<4)
            {
                x=4;y=1;
            }
            else
                if(n.j<7)
                {
                    x=4;y=4;
                }
                else
                {
                    x=4;y=7;
                }
        }
        else
        {
            if(n.j<4)
            {
                x=7;y=1;
            }
            else
                if(n.j<7)
                {
                    x=7;y=4;
                }
                else
                {
                    x=7;y=7;
                }
        }


        for(i=x;i<=x+2;i++)//判断小方块中是否存在p
        {
            for(j=y;j<=y+2;j++)
            {
                if(map[i][j]==p)
                    return 0;
            }
        }

        return 1;
}



    


void dfs(int sum)
{
    if(sum==k)
    {
        foat=1;

        for(int i=1;i<=9;i++)//全部填满后,必须在这输出,否则回溯后,数据还原。
        {
            for( int j=1;j<=8;j++)
            {
                cout<<map[i][j]<<" ";
            }
            cout<<map[i][9]<<endl;
        }

        return ;
    }
    else
    {
        for(int i=1;i<=9;i++)
        {
            if(foat==1)
                break;
            if(check(node[sum],i))
            {
                map[node[sum].i][node[sum].j]=i;//填格
                dfs(sum+1);
                map[node[sum].i][node[sum].j]=-1;//回溯
            }
        }
    }
    return ;
}


int main()
{
    char ch;
    int c=0;

    while(cin>>ch)
    { 
        memset(node,0,sizeof(node));
        
        int i,j;
        for(i=1;i<=9;i++)
        {
            for(j=1;j<=9;j++)
            {
                if(i!=1||j!=1)//因为第一个小格已经输入,所以不需再次输入
                {
                    cin>>ch;
                }

                if(ch!='?')
                    map[i][j]=ch-'0';
                else
                {
                    node[k].i=i;
                    node[k].j=j;
                    k++;
                    map[i][j]=-1;
                }
            }
        }

        if(c++)
            cout<<endl;

        foat=0;
        k=1; 
        dfs(1);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zgfailmr/p/2680756.html