与上面对比.

来源:互联网 发布:如何下载网页上js文件 编辑:程序博客网 时间:2024/05/01 17:32
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<iostream>
#define inf 0x3f3f3f
using namespace std;
char a[100][100];
int dir[4][2]={{1,0},{0,1},{0,-1},{-1,0}};
int begx,begy,arrx,arry,row,col,t,wall;
int vis;
void dfs(int begx , int begy , int cnt)
{
    int temp;
   // printf("^%d  %d   %d  %d\n",t,cnt,begx,begy);
    if(begx == arrx && begy == arry && cnt == t)
      vis = 1;
    if(vis == 1)return ;
    temp = (t-cnt) - ( abs(arrx-begx)+abs(arry-begy) );
   // printf("%d\n",temp);
   //printf("%d\n",temp);
    if(temp < 0 || temp & 1)return ;
    //printf("%d\n",temp);
    //剪枝1,如果没有考虑X的情况下跑最短路也不能达到,返回。
    //剪枝2.如果所需走的路和T不适同奇偶.也返回.
    if(begx < 0 || begy < 0 || begx >= row || begy >= col)
      return;//边界条件和X限制.
     // for(int j = 0 ; j < row ; j++)printf("%s\n",a[j]);
     //for(int i = 0 ; i < row ; i++)printf("%s\n",a[i]);
    for(int i = 0 ; i < 4 ; i++)
    {
        if(begx+dir[i][0] >= 0 && begx+dir[i][0] < row && begy+dir[i][1] >= 0 && begy+dir[i][1] < col)
        {
            if(a[begx+dir[i][0]][begy+dir[i][1]] != 'X')
            {
               a[begx+dir[i][0]][begy+dir[i][1]] = 'X';
             // printf(" %d&&%d\n",cnt,m);
               dfs(begx+dir[i][0],begy+dir[i][1],cnt+1);
               a[begx+dir[i][0]][begy+dir[i][1]] = '.';
            }
        }


    }
    return;
}
int main()
{
    while(scanf("%d%d%d",&row,&col,&t) && row != 0)
    {
        wall = 0;
        for(int i = 0 ; i < row ; i++)
        {
            scanf("%s",a[i]);
        }
        vis = 0 ;
        for(int i = 0 ; i < row ; i++)
        {
            for(int j = 0 ; j < col ; j++)
            {
                if(a[i][j] == 'S')
                {
                    begx = i ;
                    begy = j ;
                }
                if(a[i][j] == 'D')
                {
                    arrx = i ;
                    arry = j ;
                }
                if(a[i][j] == 'X')
                wall++;
            }
        }
        a[begx][begy] = 'X';//先把起点变成X,不然出去了要回来.
        if(row*col - wall > t)这里因为起点在,所以等于是不成立的.这里把等于加上就变成500多了.这样子是140MS
        dfs(begx,begy,0);
        if(vis == 1)printf("YES\n");
        else printf("NO\n");
    }
}
原创粉丝点击