【DFS】POJ 2044

http://poj.org/problem?id=2044

#define N 366
bool flag[8][8][8][8][10][N];//前四个是四个角的状态,第五个是云的左上角的位置,最后一个是第几天
int day[N];
int n;
int d[9][2] = { {0,0},//九个位置
                {-1,0},{-2,0},
                {1,0},{2,0},
                {0,-1},{0,-2},
                {0,1},{0,2}
              };

//四个角7天内没雨,return false
//该状态已存在,return false
//是否有限制不能下雨
bool chk(int x,int y,int num,int *a){
    if(a[1]==7||a[2]==7||a[3]==7||a[4]==7)return false;
    int pos = 3*x+y;
    if(flag[a[1]][a[2]][a[3]][a[4]][pos][num] == true)return false;
    int tmp = (1<<(15-4*x-y)) | (1<<(15-4*(x+1)-y)) | (1<<(15-4*x-(y+1))) | (1<<(15-4*(x+1)-(y+1)));
    if((day[num]&tmp) != 0)return false;
    flag[a[1]][a[2]][a[3]][a[4]][pos][num] = true;
    return true;
}

bool dfs(int x,int y,int num,int *a){
    if(num==n)return true;
    if(chk(x,y,num,a) == false)return false;
    int i,j,k;
    for(i=0;i<9;i++){//(0,0)-->(2,2)
        int xx = x+d[i][0];
        int yy = y+d[i][1];
        if(xx<0 || xx>2 || yy<0 || yy>2)continue;
        int b[5];
        b[1] = a[1]+1;
        b[2] = a[2]+1;
        b[3] = a[3]+1;
        b[4] = a[4]+1;
        if(xx==0 && yy==0)b[1] = 0;
        if(xx==0 && yy==2)b[2] = 0;
        if(xx==2 && yy==0)b[3] = 0;
        if(xx==2 && yy==2)b[4] = 0;
        if(dfs(xx,yy,num+1,b))return true;
    }
    return false;
}

int main(){
    while(scanf("%d",&n) && n){
        int i,j;
        memset(day,0,sizeof(day));
        memset(flag,false,sizeof(flag));
        for(i=0;i<n;i++){
            for(j=1;j<=16;j++){
                int x;
                scanf("%d",&x);
                day[i] = (day[i]<<1) | x;
            }
        }
        int a[5];//记录四个角没有下雨天数
        a[1] = a[2] = a[3] = a[4] = 1;
        if(dfs(1,1,0,a))printf("1\n");
        else printf("0\n");
    }
    return 0;
}

    原文作者:DFS
    原文地址: https://blog.csdn.net/leolin_/article/details/7234111
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞