标签:
Description
Input
Output
/*剪枝很重要,可走的格数小于时间则减去,然后就是奇偶性剪枝
可以把map看成这样:
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
从为 0 的格子走一步,必然走向为 1 的格子
从为 1 的格子走一步,必然走向为 0 的格子
即:
 0 ->1或1->0 必然是奇数步
 0->0 走1->1 必然是偶数步
所以当遇到从 0 走向 0 但是要求时间是奇数的,或者, 从 1 走向 0 但是要求时间是偶数的 都可以直接判断不可达!
*/
#include <iostream>
#include <stdlib.h>
#include <cstdio>
using namespace std;
char map[8][8];
int dir[4][2]={{0,-1},{0,1},{1,0},{-1,0}};
int n,m,t,step,remain,destx,desty;
bool found;
void dfs(int ic, int jc, int tc)
{
    if(tc==t&&ic==destx&&jc==desty)
        found=true;
    if(found)return;
    int v=t-tc-abs(destx-ic)-abs(desty-jc);           //奇偶性剪枝
    if(v<0||v&1)return;                                       //if((abs(destx-ic)+abs(desty-jc))%2!=(t-tc)%2)return;
    for(int i=0;i<4;i++)
    {
        int ni=ic+dir[i][0];
        int nj=jc+dir[i][1];
        if(ni>=0&&ni<n&&nj>=0&&nj<m&&map[ni][nj]!=‘X‘)
        {
            map[ni][nj]=‘X‘;
            dfs(ni,nj,tc+1);
            map[ni][nj]=‘.‘;
        }
    }
}
int main()
{
    while(scanf("%d%d%d",&n,&m,&t)==3&&(n+m+t))
    {
        int icur,jcur;
        step=0; remain=0; found=false;
        for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
        {
           cin>>map[i][j];
           if(map[i][j]==‘S‘)
           icur=i,jcur=j;
           else if(map[i][j]==‘D‘)
          {
              remain++;
              destx=i;desty=j;
          }
           else if(map[i][j]==‘.‘) remain++;
        }
        map[icur][jcur]=‘X‘;
        if(remain>=t)
            dfs(icur,jcur,0);
        if(found)cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
    }
    return 0;
}
标签:
原文地址:http://www.cnblogs.com/chen9510/p/4707542.html