CodeForce 540C:(DFS)

终点必须是X时才能完成,如果是“。"则意味着终点需要走两次

用mat[i][j]表示该点还能经过的次数

#include"cstdio"
#include"cstring"
#include"queue"
#include"iostream"
#define MAXN 505
using namespace std;
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
int mat[MAXN][MAXN];
int x,y,ok,mark;
char arr[MAXN];
struct point
{   int x;
    int y;
}s,e,temp;
bool dfs(point s)
{   //cout<<s.x<<'	'<<s.y<<endl;
    if(s.x==e.x&&s.y==e.y&&!mat[s.x][s.y]) {ok=1;return true;}
    if(ok) return true;
    for(int k=0;k<4;k++){
        temp.x=s.x+dx[k];
        temp.y=s.y+dy[k];
        //cout<<mat[temp.x][temp.y]<<'	'<<endl;
        if(temp.x>=0&&temp.x<x&&temp.y>=0&&temp.y<y&&mat[temp.x][temp.y]){
            mat[temp.x][temp.y]--;
            if(dfs(temp)) return true;
        }
    }
    return false;
}
int main()
{   while(scanf("%d%d",&x,&y)!=EOF){
        memset(mat,0,sizeof(mat));
        for(int i=0;i<x;i++){
            scanf("%s",arr);
            for(int j=0;j<y;j++){
                if(arr[j]=='.') mat[i][j]=1;
                else mat[i][j]=0;
            }
        }
        scanf("%d%d",&s.x,&s.y);s.x--;s.y--;
        scanf("%d%d",&e.x,&e.y);e.x--;e.y--;
        ok=0;
        mark=1;
        //mat[s.x][s.y]=1;
        mat[e.x][e.y]++;
        dfs(s);
        if(ok) printf("YES
");
        else printf("NO
");
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/luxiaoming/p/4705294.html