hdu 2102 A计划 我用的是dfs

来源:互联网 发布:koala for mac 下载 编辑:程序博客网 时间:2024/05/21 07:04

hdu 2102

很久没写博客了,这道题是一道简单的搜索题,深搜广搜都可以做,我用的是深搜,但是要注意一点:剪枝

#include<iostream>#include<cstring>#include<algorithm>#include<cstdio>#include<cmath>#include<string>using namespace std;int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};char map1[20][20];char map2[20][20];bool v1[20][20],v2[20][20];int c,n,m,T,flag;void dfs(int i,int j,int s12,int t){    if(t>T) return;    if(s12==1){        if(map1[i][j]=='.' || map1[i][j]=='S'){ ///继续寻找            for(int k=0;k<=3;k++)            {                int x = i+dir[k][0];                int y = j+dir[k][1];                if(x>=1 && x<= n && y>=1 && y<=m )                {                    if(v1[x][y]==0){                        v1[x][y] = 1;                        dfs(x,y,1,t+1);                        v1[x][y] = 0;                    }                }            }        }        else if(map1[i][j]=='#'){ ///穿越             v1[i][j] = 1;             if(v2[i][j]==0)             {                v2[i][j]=1;                dfs(i,j,2,t);                v2[i][j]=0;             }        }        else if(map1[i][j]=='*'){            return ;        }        else if(map1[i][j]=='P'){            if(t<=T) {                flag = 1;                return ;            }            else return;        }    }    else if(s12==2)    {        if(map2[i][j]=='.'){             for(int k=0;k<=3;k++)            {                int x = i+dir[k][0];                int y = j+dir[k][1];                if(x>=1 && x<= n && y>=1 && y<=m )                {                    if(v2[x][y]==0){                        v2[x][y] = 1;                        dfs(x,y,2,t+1);                        v2[x][y] = 0;                    }                }            }        }        else if(map2[i][j]=='#'){ ///穿越             v2[i][j] = 1;             if(v1[i][j]==0)             {                 v1[i][j] = 1;                  dfs(i,j,1,t);                  v1[i][j] = 0;             }        }        else if(map2[i][j]=='*') return;        else if(map2[i][j]=='P'){                if(t<=T) {                    flag = 1;                    return ;                }            else return ;        }    }   return;}int main(){    scanf("%d",&c);    while(c--)    {        memset(v1,0,sizeof(v1));        memset(v2,0,sizeof(v2));        flag = 0;        v1[1][1] = 1;        scanf("%d%d%d",&n,&m,&T);        for(int i=1;i<=n;i++)            for(int j=1;j<=m;j++)        {            cin>>map1[i][j];        }         for(int i=1;i<=n;i++)            for(int j=1;j<=m;j++)        {            cin>>map2[i][j];        }        dfs(1,1,1,0);        if(flag) printf("YES\n");        else printf("NO\n");    }    return 0;}


原创粉丝点击