深搜_奇偶减枝(HDU_1010)

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define M    8

char map[M][M];
int move[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int n,m,sx,sy,ex,ey,t,flag,count;

void init()
{
    for(int i=0;i<n;i++)
        scanf("%s",map[i]);

    for(i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if('S'==map[i][j])
            {
                sx=i;    sy=j;    map[i][j]='X';
            }
            else if('.'==map[i][j])
            {
                count++;
            }
            else if('D'==map[i][j])
            {
                ex=i;    ey=j;    
            }
        }
    }
}

int jud(int row,int col)
{
    if(row>=0 && row<n && col>=0 && col<m && map[row][col]!='X')    return 1;
    return 0;
}

void dfs(int row,int col,int step)
{
    if(flag)    return ;

    if(row==ex && col==ey && step==t)
    {
        flag=1;    return ;
    }

    if((t-step)%2 != (abs(row-ex)+abs(col-ey))%2)  //奇偶减枝法
        return ;

    if(abs(row-ex)+abs(col-ey) > t-step)
        return;

    for(int i=0;i<4;i++)
    {
        int _row=row+move[i][0];
        int _col=col+move[i][1];
        if(jud(_row,_col))
        {
            map[_row][_col]='X';
            step++;
            dfs(_row,_col,step);
            step--;
            map[_row][_col]='.';
        }
    }
}


int main()
{
    #ifdef __LOCAL
    freopen("in.txt","r",stdin);
    #endif
    while(scanf("%d%d%d",&n,&m,&t) && (n || m ||t))
    {
        count=flag=0;
        init();
        if(count+1<t)
        {
            printf("NO\n");    continue;
        }
        dfs(sx,sy,0);
        if(flag)    printf("YES\n");
        else        printf("NO\n");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lk1993/p/3033851.html