【TOJ 3305】 Hero In Maze II

describe

500 years ago, Jesse was the most prominent swordsman in our country. He is handsome and witty ^_^.
Suddenly one day, Jesse's beloved princess is trapped in a huge labyrinth by the devil. It's been two days since Jesse heard the news. He hurried to the labyrinth and started looking for the whereabouts of the princess. The headache is that Jesse is a directional person, so he can't make too many turns while walking, or he will faint. We assume that Jesse and the princess are in an open space. Initially, the direction Jesse is facing is undetermined. He can choose any of the 4 directions to start, and it does not count as a turn. I hope you can help him judge whether he has a chance to find the beloved princess. 

enter

Questions include multiple sets of test data.

The first line is an integer T (1 ≤ T ≤ 100), indicating the number of test data, followed by T groups of test data.

Each set of test data starts with two integers N, M, K (1<=N, M≤100, 0<K<=10), which represent the height and length of the maze and the maximum number of turns that Jesse can turn, (tight Then there are N lines and M columns of characters, consisting of ".", "*", "P", "S". Where 
"." represents a walkable space. 
"*" represents a wall, which Jesse cannot pass through. 
"P " is the location of the princess. 
"S" is the starting position of Jesse. 
Jesse can only choose to take a step in any direction of "up, down, left, and right" in each time period.

output

Output "YES" if Jesse can find the princess before she faints, otherwise output "NO".

sample input

2
5 5 1
P..**
*.**.
S....
.....
*....
5 5 2
P..**
*.**.
S....
.....
*....

Sample output

NO
YES

answer

We set four directions, which are 0, 1, 2, 3

Note that while searching deeply, set the initial direction to -1 and the initial number of turns to -1

In this way, when you enter the deep search at the beginning, you can return all the first direction changes to 0.

#include<bits/stdc++.h>
using namespace std;
int n,m,k,flag,dir[4][2]={-1,0,0,-1,0,1,1,0};
char G[105][105];
void dfs(int x,int y,int d,int s)
{
    if(flag||s>k)
        return;
    if(G[x][y]=='P')
    {
        flag=1;
        return;
    }
    G[x][y]='*';
    for(int i=0;i<4;i++)
    {
        int px=x+dir[i][0];
        int py=y+dir[i][1];
        if(px>=1&&px<=n&&py>=1&&py<=m&&G[px][py]!='*')
        {
            if(d==i)
                dfs(px,py,d,s);
            else dfs(px,py,i,s+1);
        }
    }
    G[x][y]='.';
}
intmain ()
{
    int i,j,t;
    cin>>t;
    while(t--)
    {
        cin>>n>>m>>k;
        flag=0;
        for(i=1;i<=n;i++)
            scanf("%s",G[i]+1);
        for(i=1;i<=n;i++)
            for(j=1;j<=m;j++)
                if(G[i][j]=='S')
                    dfs(i,j,-1,-1);
        if(flag)
            printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326268470&siteId=291194637