Tempter of the Bone 奇偶剪枝(深搜)

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

bool visit[8][8];
char map[8][8];
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
int Time,row,col,flag,sx,sy,ex,ey;
void dfs(int x,int y,int step)
{
     int tx,ty,Min,tstep;
     if(map[x][y]=='X')
       return ;
     if(flag)
       return ;
     if(x==ex&&y==ey&&step==Time)
       {flag=1;return;}
     if(step>=Time)
        return ;
     Min=(int)(fabs((double)(x-ex))+fabs((double)(y-ey)));
     if(Min>Time-step)
        return ;
     if(Min%2!=(Time-step)%2)return;
     if(map[ex+1][ey]!='.'&&map[ex-1][ey]!='.'&&map[ex][ey+1]!='.'&&map[ex][ey-1]!='.')return;
     for(int i=0;i<4;i++)
     {
        tx=x+dx[i];
        ty=y+dy[i];
        tstep=step+1;
        if(tx<0||tx>=row||ty<0||ty>=col) continue ;
        if(!visit[tx][ty])
        {
           visit[tx][ty]=true;
          dfs(tx,ty,tstep); 
           visit[tx][ty]=false;
           if(flag)return;
        }

     }
     
     
}
int main()
{  
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    int i,j,op,num;
    while(scanf("%d %d %d",&row,&col,&Time)==3)
    {
       if(row+col+Time==0)
         break;
         num=0;
         memset(visit,false,sizeof(visit));
       for(i=0;i<row;i++)
       {
              getchar();           
        for(j=0;j<col;j++)
        {
          scanf("%c",&map[i][j]);
          if(map[i][j]=='S'){ sx=i; sy=j;}
          else if(map[i][j]=='D') { ex=i; ey=j;}
           else num++;
        }
        
       }
        getchar();
    
       if(num<Time-1||abs(sx-ex)+abs(sy-ey)>Time||( sx + sy + ex + ey +Time )%2==1)
       {
          printf("NO\n");
          continue;
       }
      /* for(i=0;i<row;i++)
       {
       
        for(j=0;j<col;j++)
        {
          printf("%c",map[i][j]);
           
        }
         printf("\n");
       }
       */
       flag=0;
       visit[sx][sy]=true;
       dfs(sx,sy,0);
       if(flag)
          printf("YES\n");
       else
          printf("NO\n");                        
    }   
   return 0;
}

你可能感兴趣的:(Algorithm,c,include,iostream)